c# - 在不知道泛型类型的情况下将对象添加到集合中

标签 c# generics collections interface

class Program
{
    public static void Main(string[] args)
    {
        List<MyInterface> myList = new List<MyInterface>();

        myList.Add(new MyClass<int>());

        foreach (MyInterface item in myList)
        {
            (MyClass)item).Foo(); // <---- Critical Line
        }
    }
}

interface MyInterface { }

class MyClass<T> : MyInterface
{
    public MyClass() { }
    public void Foo() { DoSomething(); }
}

我想在不知道对象的确切(通用)类型的情况下使用 MyClassFoo() 方法。有没有办法调用它呢?我会在编译代码时知道 T,那么我是否可以将它存储在通过 InterfaceB 实现的属性中?

感谢您的帮助!

编辑: 抱歉不清楚;还有其他实现 MyInterface 的类,我正在检查项目的类型是否为 ClassB,所以我不能将 Foo() 放入 MyInterface.

最佳答案

为了静态引用ClassB<T>您需要在代码中指定通用参数。您不能使用名称 ClassB因为那将引用一个名为 ClassB 的非通用类.

另一种方法是将您需要的信息添加到 InterfaceB 中因为它不需要通用参数

interface InterfaceB 
{
  InterfaceA FooUntyped();
}

...

foreach (InterfaceB item in bList) {
  aList.Add(item.FooUntyped());
}

关于c# - 在不知道泛型类型的情况下将对象添加到集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15452281/

相关文章:

c# - 在 C# 中读取 Protobuf 消息

c# - win api 和 c# - 桌面

linq - 使用在运行时解析的类型调用 System.Linq.Queryable 方法

scala - Typeclass 和 scala 集合接口(interface)

c# - 如何对返回 void 的方法进行单元测试?

generics - 如何限制 Rust 中特征的通用实现?

ios - 如何声明具有符合协议(protocol)的具体返回类型的函数?

arrays - Scala 中高效的二维数组列提取

collections - MFC:重写 CMap<> 对象的 HashKey() 的正确方法?

c# - 在 UWP、MVVM 中实现周期性进程