Covariance and contravariance real world example

后端 未结 9 1993
醉梦人生
醉梦人生 2020-11-22 16:57

I\'m having a little trouble understanding how I would use covariance and contravariance in the real world.

So far, the only examples I\'ve seen have been the same o

9条回答
  •  长发绾君心
    2020-11-22 17:30

    From MSDN

    The following code example shows covariance and contravariance support for method groups

    static object GetObject() { return null; }
    static void SetObject(object obj) { }
    
    static string GetString() { return ""; }
    static void SetString(string str) { }
    
    static void Test()
    {
        // Covariance. A delegate specifies a return type as object, 
        // but you can assign a method that returns a string.
        Func del = GetString;
    
        // Contravariance. A delegate specifies a parameter type as string, 
        // but you can assign a method that takes an object.
        Action del2 = SetObject;
    }
    
        

    提交回复
    热议问题