具有泛型参数类型的抽象类列表?

问题描述 投票:0回答:1

假设我有这些课程:

public abstract class Thing<T> { }

public class Str : Thing<string> { }

public class Boo : Thing<bool> { }

我想创建ListThing

这是我想做的示例(无效的C#代码):

new List<Something>()
{
    new Str(),
    new Boo()
};

我该怎么做,甚至有可能吗?

我找到了this,但似乎无法正确理解任何建议的答案。

c# abstract-class
1个回答
1
投票

要满足List<Something>,则Thing<T>必须继承Something。您所链接的帖子中的答案提供了解决方案:您需要引入一个非通用基类。

public abstract class Something { }
public abstract class Thing<T>: Something { }

public class Str : Thing<string> { }
public class Boo : Thing<bool> { }

new List<Something>()
{
    new Str(),
    new Boo()
};

© www.soinside.com 2019 - 2024. All rights reserved.