c# - 是否可以在 C# 中使用无类型泛型列表?

标签 c# generics list

我正在尝试以下设计但没有成功:

abstract class Foo<T>
{
    abstract T Output { get; }
}

class Bar
{
    List<Foo> Foos;
}

我不喜欢使用数组列表,因为我必须使用不安全的转换来获取类型。我希望输入 Foo 以便“输出”不仅仅是一个对象,在这种情况下我还必须使用不安全的转换。

在我的代码中,我使用 Foo untyped 和 Output 作为一个对象。

最佳答案

如果我没理解错的话,你想要一个 Foo 的列表具有不同类型 Output 的对象对吧?由于这些输出的类型不同,因此您无论如何都必须在此处使用强制转换。

但是,以下想法可能会有所帮助。您如何声明一个名为 IFoo 的非通用接口(interface)? :¹

public interface IFoo
{
    object Output { get; }
}

然后在你的抽象类中实现它:

abstract class Foo<T> : IFoo
{
    abstract T Output { get; }
    object IFoo.Output { get { return Output; } }
}

然后你可以声明一个列表 IFoo小号:

class Bar
{
    List<IFoo> Foos;
}

访问这些 foo 时,您可以通过接口(interface)将输出检索为对象:

var myObject = Foos[0].Output;     // type ‘object’

或者如果您知道它只能是几种特定类型之一,您可以尝试发现真实类型:

if (Foos[0] is Foo<string>)
    var myString = ((Foo<string>) Foos[0]).Output;   // type ‘string’

您甚至可以根据类型进行过滤,例如:

// Type ‘IEnumerable<string>’ (rather than ‘IEnumerable<object>’)!
var stringFoos = Foos.OfType<Foo<string>>().Select(f => f.Output);

¹ 您也可以将其设为名为 Foo 的抽象基类并且有Foo<T>从中得出。在这种情况下,您需要标记 Foo<T>.Outputnew关键字并使用 base.Output访问抽象基成员。

关于c# - 是否可以在 C# 中使用无类型泛型列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3613857/

相关文章:

创建或 isinstance 的 Python 泛型检查其类型参数

python - 如何从列表中删除项目及其在其他列表中的关联项目

java - 类型不匹配 : cannot convert from HashMap<Integer, Item> 到 HashMap<Integer,Item>

java - List<String> 无法转换为 List<?>

c# - 如何从 C# 中的嵌套泛型类继承泛型类

c# - 如何在未安装 Visual Studio 的计算机上安装 Windows 服务?

java - 如何设置推断类型列表 getter 和 setter?

pandas - 将制表符和换行符分隔的字符串转换为pandas数据框

c# - 如何使用 Entity Framework 关联来自多个上下文的对象

c# - 从 BindingExpression 获取源属性类型