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(); }
}
我想在不知道对象的确切(通用)类型的情况下使用 MyClass
的 Foo()
方法。有没有办法调用它呢?我会在编译代码时知道 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/