Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.ObjectModel;
- using System.Linq;
- namespace インデクサにデリゲート {
- class Program {
- static void Main(string[] args) {
- SampleCollection sample = SampleCollection.My;
- sample.Add(new Hoge() { ID = 1, Name = "A" });
- sample.Add(new Hoge() { ID = 2, Name = "B" });
- sample.Add(new Hoge() { ID = 3, Name = "C" });
- sample.Add(new Hoge() { ID = 4, Name = "D" });
- sample.Add(new Hoge() { ID = 5, Name = "E" });
- sample.Add(new Hoge() { ID = 6, Name = "F" });
- //sample.Add(new Hoge() { ID = 3, Name = "G" }); //エラー
- var r1 = sample[x => x.ID == 2];
- Console.WriteLine("{0}:{1}", r1.ID, r1.Name); //2:B
- var r2 = sample[x => x.Name == "F"];
- Console.WriteLine("{0}:{1}", r2.ID, r2.Name); //6:F
- //var r3 = sample[x => x.ID == 100];//エラー
- Console.Read();
- }
- }
- public class SampleCollection : KeyedCollection<int, Hoge> {
- static SampleCollection _this;
- private SampleCollection() {
- }
- ~SampleCollection() {
- if (_this != null) {
- _this.Clear();
- _this = null;
- };
- }
- public static SampleCollection My {
- get {
- if (_this == null) _this = new SampleCollection();
- return _this;
- }
- }
- public Hoge this[Func<Hoge, bool> predicate] {
- get { return _this.First(predicate); }
- }
- protected override int GetKeyForItem(Hoge item) {
- return item.ID;
- }
- }
- public class Hoge {
- public int ID { get; set; }
- public string Name { get; set; }
- }
- }
Add Comment
Please, Sign In to add comment