[英]Generic Base Class with Constructor
I have a generic class that looks like this: 我有一个通用类,如下所示:
public class DataServiceBase<T> : Screen where T : EntityManager, new (){
private T _entityManager;
public T EntityManager {
get {
if (_entityManager == null)
{
_entityManager = new T();
}
return _entityManager;
}
}
Basically all I am trying to do is create an EntityManager of if it doesn't exist. 基本上我所要做的就是创建一个EntityManager,如果它不存在的话。 This actually works fine.
这实际上很好。 However, I need to modify this as T no longer has a parameterizerless constructor.
但是,我需要修改它,因为T不再具有无参数化构造函数。 And so I can't use this methodology at all.
所以我根本不能使用这种方法。
But I do need the EntityManager strongly typed at the derived level of the DataService as different entity managers handled different entities. 但我确实需要在DataService的派生级别强类型化EntityManager,因为不同的实体管理器处理不同的实体。
I am not sure how to resolve this. 我不知道如何解决这个问题。 One alternative I have tried is:
我尝试过的另一种选择是:
public DataServiceBase(EntityManager entityManager) {
this._entityManager = entityManager;
}
In other words, I pass it into the constructor, but now I no longer have the property strong typed. 换句话说,我将它传递给构造函数,但现在我不再具有强类型的属性。
Greg 格雷格
Just make the constructor argument take the generic type also 只需使构造函数参数也采用泛型类型
public DataServiceBase(T entityManager) {
this._entityManager = entityManager;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.