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

天涯浪子 提交于 2020-01-11 07:52:06

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/7210632/how-to-have-a-list-of-problembasetresult

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!