简体   繁体   English

泛型类型的异常

[英]Cast exception in generic type

public class clsA<T, T1>
    where T : class
    where T1 : class
{
    public T GetEntity()
    {
        return (T) new clsB<T1>();            
    }
}

I am getting error Cannot convert type clsB<T1> to T 我收到错误消息无法将类型clsB<T1>转换为T

Please help 请帮忙

That's because T could be anything -- string for example, and that would cause the cast to fail. 那是因为T可以是任何东西-例如string ,这将导致强制转换失败。 If T cannot be a variable type, then do not include it in the generic argument list. 如果T不能为变量类型,则不要将其包括在通用参数列表中。

If you want to allow T to be clsB<T1> or any subtype, and you want to construct an instance of that class, then do this instead: 如果要允许TclsB<T1>或任何子类型,并且要构造该类的实例,请执行以下操作:

public class clsA<T, T1>
    where T : clsB<T1>, new()
    where T1 : class
{
    public T GetEntity()
    {
        return new T();
    }
}

Then, given the type: 然后,给定类型:

public class clsC : clsB<string> { }

Invoking GetEntity() on an object of type clsA<clsC, string> will construct and return an instance of clsC . 在类型为clsA<clsC, string>的对象上调用GetEntity()将构造并返回clsC的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM