Guest User

Untitled

a guest
Jul 21st, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.Linq;
  4.  
  5. namespace インデクサにデリゲート {
  6. class Program {
  7. static void Main(string[] args) {
  8. SampleCollection sample = SampleCollection.My;
  9. sample.Add(new Hoge() { ID = 1, Name = "A" });
  10. sample.Add(new Hoge() { ID = 2, Name = "B" });
  11. sample.Add(new Hoge() { ID = 3, Name = "C" });
  12. sample.Add(new Hoge() { ID = 4, Name = "D" });
  13. sample.Add(new Hoge() { ID = 5, Name = "E" });
  14. sample.Add(new Hoge() { ID = 6, Name = "F" });
  15. //sample.Add(new Hoge() { ID = 3, Name = "G" }); //エラー
  16.  
  17. var r1 = sample[x => x.ID == 2];
  18. Console.WriteLine("{0}:{1}", r1.ID, r1.Name); //2:B
  19.  
  20. var r2 = sample[x => x.Name == "F"];
  21. Console.WriteLine("{0}:{1}", r2.ID, r2.Name); //6:F
  22.  
  23. //var r3 = sample[x => x.ID == 100];//エラー
  24.  
  25. Console.Read();
  26. }
  27. }
  28.  
  29. public class SampleCollection : KeyedCollection<int, Hoge> {
  30. static SampleCollection _this;
  31.  
  32. private SampleCollection() {
  33. }
  34.  
  35. ~SampleCollection() {
  36. if (_this != null) {
  37. _this.Clear();
  38. _this = null;
  39. };
  40. }
  41.  
  42. public static SampleCollection My {
  43. get {
  44. if (_this == null) _this = new SampleCollection();
  45. return _this;
  46. }
  47. }
  48.  
  49. public Hoge this[Func<Hoge, bool> predicate] {
  50. get { return _this.First(predicate); }
  51. }
  52.  
  53. protected override int GetKeyForItem(Hoge item) {
  54. return item.ID;
  55. }
  56. }
  57.  
  58. public class Hoge {
  59. public int ID { get; set; }
  60. public string Name { get; set; }
  61. }
  62. }
Add Comment
Please, Sign In to add comment