.NET 4 supports co- and contravariance. However, only reference types are supported, not value types. Why is that?
相关问题
- IPAddress.[Try]Parse parses 192.168 to 192.0.0.168
- Lookup Class In LINQ, What is the underlying data
- Get Types defined in an assembly only [duplicate]
- The new IntPtr.Add method - am I missing the point
- .net 4 string[] parameter default value setting
相关文章
- Publish is not transforming web.config?
- Default for generic type? [duplicate]
- Cast List of Anonymous type to List of Dynamic Obj
- Replace relative urls to absolute
- Sign data using smart card's private key with
- Migrating ASP.NET (MVC 2) on .NET 3.5 over to .NET
- Entity Framework POCO objects
- How to set a binary attribute when using a Account
Both forms of variance are defined in terms of inheritance: value types aren't inherited.
Jon is right; to just expand on that a bit. Suppose you have
Suppose that were legal. The compiler generates a boxing instruction; the third line is effectively:
Clearly the result stored in o2 should be a boxed int. Where is the boxing instruction? It cannot be after the call to f2, because that thing is guaranteed to return an object already. It cannot be in the call to f2, because the call to f2 is actually a call to f1, and f1 guarantees that it returns an unboxed int.
So the boxing instruction cannot happen after the call returns, and it cannot happen before the call returns, and therefore it cannot happen at all, and therefore this must be illegal. There is no reference conversion from
Func<int>
toFunc<object>
.Basically the CLR needs to know that it can treat a value of the "source" type as a value of the "target" type without performing any extra conversions - to put it simply, the bit pattern for the source value has to be valid as the target value. The representations have to be the same. Otherwise the CLR would need to have extra information to perform the right conversions at the right time.
Eric Lippert has blogged about representation and identity - see that post for more information (as ever :).