Possible Duplicate:
polymorphic resolution of generic parameters in Unity registerType
This is probably obvious. But can someone tell me why this is not valid code?
The compiler says it can't convert Class1<string>
to Class1<object>
.
Is upcasting this way not allowed with generics? If so, why not?
namespace Test
{
public class Tests
{
public void Test()
{
Class1<object> objectClass1 = new Class1<string>(开发者_运维知识库);
}
}
class Class1<T>
{
}
}
Have a look at
Covariance and Contravariance in Generics.
Eric Lippert has a series of blog posts on this subject.
String, Int32, and so on are Struct types, while object, Person and so on are class objects for C#. For this reason, when you create generics, you have to specify a constraint if you plan to use casting features. So, you can use
public void Method<T>() where T : class
or
public void Method<T>() where T : struct
精彩评论