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. This actually works fine. However, I need to modify this as T no longer has a parameterizerless constructor. 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.
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
A generic constructor is a constructor that has at least one parameter of a generic type. We'll see that generic constructors don't have to be in a generic class, and not all constructors in a generic class have to be generic.
base (C# Reference)A base class access is permitted only in a constructor, an instance method, or an instance property accessor. It is an error to use the base keyword from within a static method. The base class that is accessed is the base class specified in the class declaration.
Can we have a generic constructor? No, generic constructors are not allowed.
When objects are constructed, it is always first construct base class subobject, therefore, base class constructor is called first, then call derived class constructors. The reason is that derived class objects contain subobjects inherited from base class.
Just make the constructor argument take the generic type also
public DataServiceBase(T entityManager) {
this._entityManager = entityManager;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With