Reputation: 973
I've a generic base class where generic type is class and other related inherited class:
public class BaseClass<T> where T : class
{
virtual void DoWork(){..}
virtual void DoAnotherWork(){..}
}
public class SomeInherit<Person> : BaseClass<Person>
{
//...
}
public class OtherInherit<Car> : BaseClass<Car>
{
// override something..
}
Then, I've a BaseClassManager which should be able to load some BaseClass inherited by some co-worker via reflection:
public class BaseClassManager
{
public BaseClass<TItem> LoadBaseClass<T>() where T : BaseClass<???>
{
// how can create an instance of T?
// TItem : class
// T : BaseClass
// -------------> in reality, it should be: T<TItem> (just as BaseClass<Person>)
}
}
Is there any way to accomplish that..?
Upvotes: 2
Views: 761
Reputation: 217313
You need to define a second type parameter for where T : BaseClass<???>
.
You can use the new()
constraint to allow the method to create instances of a generic type.
public TBaseClass LoadBaseClass<TBaseClass, TItem>()
where TBaseClass : BaseClass<TItem>, new()
where TItem : class
{
return new TBaseClass();
}
Usage:
SomeInherit<Foo> result = LoadBaseClass<SomeInherit<Foo>, Foo>();
Upvotes: 5