开发者

How to have a list of ProblemBase<TResult>? [duplicate]

开发者 https://www.devze.com 2023-03-31 06:37 出处:网络
This question already 开发者_如何学Chas answers here: Closed 11 years ago. Possible Duplicate: How do I create a list of objects that inherit from the same generic class with varying types?
This question already 开发者_如何学Chas answers here: Closed 11 years ago.

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; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消