zoukankan      html  css  js  c++  java
  • 逆变和协变 in,out有关

    逆变和协变,关键字在泛型接口和委托中使用
    亲测:

    Func<Object,Object> a = Func<string,string>;// ERROR,in不可协变
    Func<string,Object> a = Func<string,string>;//Right,out可协变
    //协变:out
    IEnumerable<string> strings = new List<string>(); 
    IEnumerable<object> objects = strings;
    
    static string SetString(string o) { return "str"; }
    //逆变:in
    Action<object> actObject = SetObject; 
    Action<string> actString = actObject; 
    Func<string,string> funcString = SetString;
    //协变:out
    Func<string, object> FuncObject = funcString;//out协变

    out,in泛型修饰符,泛型在声明的尖括号中<out T><in T>
    out,in还可用作参数修饰符,在小括号中(),默认是in,ref侧重修改.out侧重输出。
    out——协变
    in——逆变
    所以如果有一个泛型参数标记为out,则代表它是用来输出的,只能作为结果返回,而如果有一个泛型参数标记为in,则代表它是用来输入的,也就是它只能作为参数。
    总之一句话,在泛型中,如果函数类型参数是只读或者只写,那么就可以使用协变或者逆变。如果类型参数无法保证只读或只写,这种类型参数(List)既不能协变也不能逆变,只能精确类型匹配。记住这个将是理解协变和逆变的关键。


    下面是一些常用的泛型类或接口:

    public interface IEnumerable<[NullableAttribute(2)] out T> : IEnumerable
    
    //List没有in和out修饰泛型,只能精确匹配,而不能逆变和协变。
    public class List<[NullableAttribute(2)] T>
    
    
    public delegate TResult Func<[NullableAttribute(2)] in T, [NullableAttribute(2)] out TResult>(T arg);
    
    
    public delegate void Action<[NullableAttribute(2)] in T>(T obj);

    想转化List为协变,需要以下操作:
    List<Animal> lstAnimal2 = lstDogs.Select(d => (Animal)d).ToList();

    List<Dog> 和 List<Animal> 是两个不同的类。是由泛型List<T>类型生成的两个不同类型。

    java是同一个类,所以没有协变和逆变,List中的泛型是不变的【没有in 和 out】。

    协变——返回和输出out

    逆变——输入,传入派生类照样可以操作不报错,in

    源码,是痛苦的,又是快乐的,如果没有这痛苦,也就没有了这快乐!
  • 相关阅读:
    CCF CSP 201609-2 火车购票
    CCF CSP 201409-2 画图
    CCF CSP 201409-2 画图
    CCF CSP 201409-4 最优配餐
    CCF CSP 201409-4 最优配餐
    CCF CSP 201503-1 图像旋转
    CCF CSP 201503-1 图像旋转
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
  • 原文地址:https://www.cnblogs.com/erlongxizhu-03/p/12886615.html
Copyright © 2011-2022 走看看