How to have a list of ProblemBase<TResult>? [duplicate]
Possible Duplicate:
How do I create a list of objects that inherit from the same generic class with varying types?
I'm using several objects where they are inherited from an abstract class. But to use the abstract class must be declara a generic datatype.
I'm having problems because I need to have a list where contains a list of ProblemBase, although each one contains a different TResult datatype.
public abstract class ProblemBase<TResult>
{
TResult[] Array;
}
And I want to get Array property. That's the problem.
This type of thing happens for me quite often. The solution I typically go with is to have a base class for ProblemBase<T>
that is type free:
public abstract class ProblemBase
{
public abstract object Result { get; }
}
public abstract class ProblemBase<TResult> : ProblemBase
{
public override object Result
{
get { return Result; }
}
new public TResult Result { get; private set; }
}
Whenever you need a collection of problems, then, you can make a collection of ProblemBase
without the generics.
If TResult
has its own required inheritance hierarchy, then you can do this instead:
public abstract class ProblemBase
{
public abstract ResultBase Result { get; }
}
public abstract class ProblemBase<TResult> : ProblemBase
where TResult : ResultBase
{
public override ResultBase Result { get { return Result; } }
new public TResult Result { get; private set; }
}
精彩评论