C#中的协变OUT和逆变

时间:2022-04-07 19:16:23

泛型接口和泛型委托中经常使用可变性

in  逆变,out  协变

从 list<string>转到list<object> 称为协变 (string 从object 派生,那么 string 转成object 是合理的,子类替换父类是合理的,)

从list<object> 转到 list<string> 称为逆变 (经object 转成string ,将父类转成子类,是不合理的,称为逆变)

1.逆变代码掩饰

  static void Main(string[] args)
{
ICovariant<Object> iobj = new Sample<Object>();
ICovariant<String> istr = new Sample<String>(); // You can assign istr to iobj because
// the ICovariant interface is covariant.
// iobj = istr;
istr = iobj; //从 object 类型转成string 类型,父类转成子类 则是逆变
Console.ReadLine();
} // Covariant interface.
interface ICovariant<in R> { } // Extending covariant interface.
interface IExtCovariant<in R> : ICovariant<R> { } // Implementing covariant interface.
class Sample<R> : ICovariant<R> { }

2.协变演示

   static void Main(string[] args)
{
ICovariant<Object> iobj = new Sample<Object>();
ICovariant<String> istr = new Sample<String>(); // You can assign istr to iobj because
// the ICovariant interface is covariant.
// iobj = istr;
iobj = istr; //从 string类型转成object类型,子类型转成父类 (里氏替换原则) 则是协变
Console.ReadLine();
} // Covariant interface.
interface ICovariant<out R> { } // Extending covariant interface.
interface IExtCovariant<out R> : ICovariant<R> { } // Implementing covariant interface.
class Sample<R> : ICovariant<R> { }