开发者

casting generics [duplicate]

开发者 https://www.devze.com 2023-03-30 19:40 出处:网络
This question already has an answer here: Closed 11 years ago. Possible Duplicate: polymorphic resolution of generic parameters in Unity registerType
This question already has an answer here: Closed 11 years ago.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消