问题描述
在C#中,我试图给私人通用变量存储在通过一个通用的方法,通过在非通用类。
中的泛型方法时应该采取那些上溯造型的基类的子类。
下面是问题的一个例子:
类BaseModel {}
类DerivedModel:BaseModel {}
类数据< T>其中T:BaseModel {}
//类是不通用的
类DataConsumer
{
//我如何将其设置为通用?
私人数据和LT; BaseModel>数据;
公共无效套装< T>(数据< T>数据),其中,T:BaseModel
{
//编译时错误:
//无法将源类型Generic.Data< T>
//为目标类型'Generic.Data< Generic.BaseModel>'
this.data =数据;
}
}
这是因为你想分配更多的派生类型数据< T>
来一个基本类型数据< BaseModel>
, ,这是不是在泛型类允许
您有两种选择:
1生成 DataConsumer
通用:
类DataConsumer< T>其中T:BaseModel
{
私人数据< T>数据;
公共无效集(数据< T>数据)
{
this.data =数据;
}
}
2 - 或,使数据
接口而不是类和标记 T
为协的类型,使用出
关键字:
接口IData的<出T>其中T:BaseModel {}
类DataConsumer
{
私人IData的< BaseModel>数据;
公共无效套装< T>(IData的< T>数据),其中,T:BaseModel
{
this.data =数据;
}
}
了解更多的
In C#, I am trying to store a private generic variable in a non-generic class that is passed in through a generic method.The generic method is supposed to take child classes that are upcast to the base class type.
Here is an example of the issue:
class BaseModel { }
class DerivedModel : BaseModel { }
class Data<T> where T : BaseModel { }
// Class is NOT generic
class DataConsumer
{
// How do I set this to generic?
private Data<BaseModel> data;
public void Set<T>(Data<T> data) where T : BaseModel
{
// Compile time error:
// Cannot convert source type 'Generic.Data<T>
// to target type 'Generic.Data<Generic.BaseModel>'
this.data = data;
}
}
That's because you're trying to assign a more derived type Data<T>
to a base type Data<BaseModel>
, which is not allowed in generic classes.
You have two options:
1- Make DataConsumer
generic:
class DataConsumer<T> where T : BaseModel
{
private Data<T> data;
public void Set(Data<T> data)
{
this.data = data;
}
}
2- OR, make Data
an interface instead of a class and mark T
as a covariant type using the out
keyword:
interface IData<out T> where T : BaseModel { }
class DataConsumer
{
private IData<BaseModel> data;
public void Set<T>(IData<T> data) where T : BaseModel
{
this.data = data;
}
}
Read more about Covariance and Contravariance in Generics here
这篇关于如何将子类分配给非泛型类中的通用字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!