对象添加到集合不知道它的泛型类型
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()
方法不知道该对象的excact(通用)类型。有什么方法可以调用它吗?编译代码时我会知道T
,所以我可以将它存储在通过InterfaceB
实现的属性中?对象添加到集合不知道它的泛型类型
感谢您的帮助!
编辑:对不起,不清楚;还有其他类实现MyInterface
,我正在检查项目的类型是ClassB,所以我不能把Foo()
放入MyInterface
。
的主要观点是,MyClass<int>
和MyClass<SomethingElse>
是100%不相关的类型,所以你不能这样对待他们一样。甚至没有部分。就好像你编写了T1
和T2
。
所以你必须创建一个通用的基类/接口或使用dynamic
。
谢谢! “动态”最终成功了。 – 2013-03-16 18:44:16
为了静态引用ClassB<T>
,您需要在代码中指定通用参数。您不能使用名称ClassB
,因为它会引用名为ClassB
的非泛型类。
的另一种方法,使这项工作是添加你需要到InterfaceB
的信息,因为它并不需要一个泛型参数
interface InterfaceB
{
InterfaceA FooUntyped();
}
...
foreach (InterfaceB item in bList) {
aList.Add(item.FooUntyped());
}
你不是遍历ClassB的项,而是interfaceB这实际上并没有指定一个Foo方法。
然而没有检查:
var itemB = item as ClassB; if (itemB != null){ itemB.Foo() }
没有'ClassB'这样的类型 - 只有* generic * type'ClassB ',并且你不能在没有提供类型参数的情况下检查它的一个实例。 – 2013-03-16 17:37:53
interface MyInterface { }
interface MyFooInterface<T>
{
List<T> Foo<T>();
}
class MyClass<T> : MyInterface, MyFooInterface<T>
{
public MyClass() { }
public List<T> Foo<T>() { DoSomething(); }
}
class MyClassB<T> : MyInfterface
{...}
...
foreach (MyFooInterface item in myList.OfType<MyFooInterface>)
{
item.Foo();
}
...
这很好,谢谢!但是,你是否也知道'Foo'返回'List
我想我是,已经更新回答 – Dima 2013-03-16 18:10:52
目前尚不清楚哪个界面对您很重要。你真的需要*'InterfaceA'和'ClassA'来证明你的问题,或者你真的只关心如何调用'Foo'? – 2013-03-16 17:25:02
@Jon Skeet你是对的。我只是把它放在我的项目中遇到问题的方式。 – 2013-03-16 17:27:30
在你的界面声明'Foo'。 – 2013-03-16 17:32:24