public void Covariance()
            {
                ICovariant <Fruit> fruit = new Covariant <Fruit>();
                ICovariant <Apple> apple = new Covariant <Apple>();

                Covariant(fruit);
                Covariant(apple); //apple is being upcasted to fruit, without the out keyword this will not compile
            }
示例#2
0
文件: Generic.cs 项目: thevur0/CSharp
        static void ContravariantAndCovariant()
        {
            IContravariant <BaseClass> iBaseClassA = new Contravariant <BaseClass>();

            iBaseClassA.Method(new DerivedClass());

            ICovariant <BaseClass> iBaseClassB = new Covariant <BaseClass>();

            iBaseClassB.Method().Print();
        }
        private static void Covariance()
        {
            ICovariant <Fruit> fruit = new Covariant <Fruit>();
            ICovariant <Fruit> apple = new Covariant <Apple>();

            // ICovariant<Apple> fruit = new Covariant<Fruit>(); // not allowed
            // Covariant<Fruit> appleNotCompiled = new Covariant<Apple>(); // won't compile
            // Implementations are always invariant, use interfaces to achieve variance
            Console.WriteLine(fruit.GetType());
            Console.WriteLine(apple.GetType());
        }
        private void CovarianceExample()
        {
            ConsoleExtensions
            .WriteColoredLine(Resources.CovarianceExampleRunning, ConsoleColor.Cyan);

            // A covariant type in an interface or delegate can be converted to a more GENERAL type.

            // Interface: ICovariant<Banana> to ICovariant<Fruit>
            ICovariant <Fruit> fruitCovariantInterface = this.bananaCovariantInterface;

            // Delegate: Covariant<Lemon> to Covariant<object>
            Covariant <object> objectCovariantDelegate = this.lemonCovariantDelegate;

            const int FruitQuality = 85;
            var       fruit        = fruitCovariantInterface.Create(FruitQuality);
            var       obj          = objectCovariantDelegate();

            Console.WriteLine(Resources.CovarianceExampleFruitColor, fruit.Name, fruit.Color);
            Console.WriteLine(Resources.CovarianceExampleObjString, nameof(obj), obj.ToString());
            Console.WriteLine();
        }
 static void Run()
 {
     ICovariant <Fruit>     apple = new Covariant <Apple>();     //because it's covariant
     IContravariant <Apple> fruit = new Contravariant <Fruit>(); //because it's contravariant
 }
示例#6
0
 public void Example()
 {
     // possible because its covariant (out keyword)
     ICovariant <Fruit> fruit = new Covariant <Apple>();
 }