C#通用协变误差

Clo*_*ver 1 c# generics covariant

以下是我的代码,我不知道为什么DateTime无法更改为Object,有什么想法可以解决这个问题?

    public class Test
    {
        public DateTime CreatedTime { get; set; }
    }
    public class Test1
    {

    }
    public class Test2 : Test1
    {
    }
    static void Main(string[] args)
    {

        Func<Test, ArgumentException> fn1 = null;
        Func<Test, Exception> fn2 = fn1;// success 

        Func<Test, Test2> fn3 = null;
        Func<Test, Test1> fn4 = fn3;//success  

        Func<Test, DateTime> expression1 = p => p.CreatedTime;
        Func<Test, object> s = expression1; // Cannot implicitly convert type 'System.Func<IlReader.Program.Test,System.DateTime>' to 'System.Func<IlReader.Program.Test,object>'    
        Func<Test, ValueType> s2 = expression1; // cannot implicatily convert .... 
    }
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 6

DateTime是一种值类型.将值类型转换为引用类型(object在本例中)是表示更改转换.它需要装箱值类型.对于参考类型,情况并非如此.CLR使用指针实现引用,并且所有指针都具有相同的大小.对派生类的引用仅被解​​释为对基类的引用.因此,您不能在值类型上使用这样的协方差.

从理论上讲,编译器可以生成一个中间函数,如:

object compilerGeneratedFunction(Test t) {
    return (object)anonymousFunctionThatReturnsDateTime(t);
    // The above cast can be implicit in C# but I made it explicit to demonstrate
    // boxing that has to be performed.
}

Func<Test, DateTime> convertedFunction = compilerGeneratedFunction;
Run Code Online (Sandbox Code Playgroud)

但是生成的委托会指向一个完全不同的函数,导致不遵守C#规范中的委托相等规则等不良内容.设计团队决定不再生成这样的功能.