代码之家  ›  专栏  ›  技术社区  ›  Aadith Ramia

理解C中的反差#

  •  1
  • Aadith Ramia  · 技术社区  · 9 年前

    我正在学习反差,并尝试了以下方法来吸收这个概念:

    interface B<T>
    {
        T h();
    }
    
    public class SomeOtherClass<T> : B<T>
    {
        public T h()
        {
            return default(T);
        }
    }
    
    public class Trial
    {
        static void Main()
        {
            SomeOtherClass<Derived> h = new SomeOtherClass<Derived>();      
            Base b = h.h();     
        }
    }
    

    我原以为这段代码会在最后一个语句中出错,并认为制作T逆变量可以修复它。然而,这是按原样工作的。这让我想知道,矛盾在哪里找到了适用性?

    2 回复  |  直到 9 年前
        1
  •  2
  •   Maarten    8 年前

    泛型变量用于接口和delgates

    将代码更改为下面的代码,您将开始收到错误

    public class Trial
    {
        static void Main()
        {
            B<Derived> h = new SomeOtherClass<Derived>();      
            B<Base> b = h; // you will get compilation error until you add out keyword in interface B     
        }
    }
    

    这里out(Contraviant)关键字是告诉编译器B的实例被认为是安全的方法

        2
  •  0
  •   Pang Ajmal PraveeN    8 年前
    using System;
    using static System.Console;
    ////
    namespace ConsoleApplication1
    {
    
        interface iContravariance<in T>
        {
            void Info(T  t);
        }
    
        class Master<T> : iContravariance<T>
        {
    
            public void Info(T insT)
            {
    
                if (insT is Parent) {
                    WriteLine("--- As Parent: ---");
                    WriteLine((insT as Parent).Method());
                }
    
                if (insT is Child) {
                    WriteLine("--- As Child: ---") ;
                    WriteLine((insT as Child).Method()); 
                }
            }
        }
    
        class Parent {
    
            public virtual String Method()
            {
                WriteLine("Parent Method()");
                return "";
            }
    
        }
    
        class Child : Parent    {
    
            public override String Method()
            {
                WriteLine("Child Method()");
                return "";
            }
        }
    
        class Client
        {
            static void Main(string[] args)
            {
                Child child      = new Child();
                Parent parent = new Parent();
    
                iContravariance<Parent> interP = new Master<Parent>();
                iContravariance<Child>   interC = interP;
    
                interC.Info(child);
    
                //interC.Info(parent); (It is compilation error.)
    
                ReadKey();
                return;
            }
        }
    }
    

    输出:

     --- As Parent: ---
     Child Method()
     --- As Child: ---
     Child Method()