コード例 #1
0
        public void Contains02()
        {
            Fruit[] fruits = { new Fruit {
                                   Name = "apple", Code = 9
                               },
                               new Fruit {
                                   Name = "orange", Code = 4
                               },
                               new Fruit {
                                   Name = "lemon", Code = 12
                               } };

            Fruit apple = new Fruit {
                Name = "apple", Code = 9
            };
            Fruit kiwi = new Fruit {
                Name = "kiwi", Code = 8
            };

            FruitComparer prodc = new FruitComparer();

            bool hasApple = fruits.Contains(apple, prodc);
            bool hasKiwi  = fruits.Contains(kiwi, prodc);

            Debug.WriteLine("Apple? " + hasApple);
            Debug.WriteLine("Kiwi? " + hasKiwi);
        }
        static void Main()
        {
            // Allowed in C# 4.0
            ICompareThings <Fruit> fc = new FruitComparer();

            Apple apple1 = new Apple();

            Apple  apple2 = new Apple();
            Orange orange = new Orange();

            // A fruit comparer can compare apples and oranges:

            bool b1 = fc.FirstIsBetter(apple1, orange);
            // or apples and apples:

            bool b2 = fc.FirstIsBetter(apple1, apple2);
            // This is legal because the interface is
            // contravariant.
            ICompareThings <Apple> ac = fc;
            // This is really a fruit comparer, so it can
            // still compare two apples

            bool b3 = ac.FirstIsBetter(apple1, apple2);
        }