c#协变 抗变

public class Fa : TranOut<Fa>, TranIn<Fa>
    {
    }
    public class son : Fa, TranOut<son>, TranIn<son>
    {

    }
    public interface TranOut<out t>
    {

    }
    public interface TranIn<in t>
    {

    }
    public class Test
    {
        public void test()
        {
            //c#4.0
            IEnumerable<Fa> sharps = new List<son>();
            Fa a = new son();
            TranOut<Fa> b = new son();
            TranIn<son> c = new Fa();

            IEnumerable<Fa> la = new List<son>();
            
        }
    }

用out作为协变关键字,in为抗变关键字

使用out可以将子类转成父类对象,in则反之


适合使用此功能实现automap
[Shìhé shǐyòng cǐ gōngnéng shíxiàn automap]
Suitable for implementing automap with this function

猜你喜欢

转载自www.cnblogs.com/ives/p/10796989.html