可能重复:
Can I declare a variable of Type<T> without specifying T at compile time?我可以在编译时声明类型为<T>的变量而不指定T吗?
目的:加载类 “为myContent” 动态。我有1个接口<T>
,1个抽象通用class<T>
。
代码:
public interface IMyObjectInterface{
}
public abstract MyAbstractObject : IMyObjectInterface{
}
public class MyObject : MyAbstractObject{
}
public interface IMyContentInterface<T> where T : MyAbstractObject
{
T MyMethod();
void MyMethod2(T);
}
public abstract MyAbstractContent<T>, IMyContentInterface<T> where T : MyAbstractObject
{
public abstract T MyMethod();
public abstract void MyMethod2(T);
}
public class MyContent : MyAbstractContent<MyObject>
{
public override MyObject MyMethod() { //do something with MyObject }
public override void MyMethod2(MyObject) { //do something with MyObject }
}
现在,我们加载:
IMyObjectInterface obj = (IMyObjectInterface)Assembly.Load("MyAssembly").CreateInstance("MyObject");
IMyContentInterface<???> content = (IMyContentInterface<???>)Assembly.Load("MyAssembly").CreateInstance("MyContent");
content.MyMethod();
如何加载???
你读过了你的其他问题的答案吗? http://stackoverflow.com/questions/2067827/can-i-declare-a-variable-of-typet-without-specifying-t-at-compile-time – Joel 2010-01-19 16:37:25
@Fabio - 对不起,我原来的答案还不够清楚,但是不可以在C#中做到这一点。如果您事先不知道'T',将无法直接访问其成员,并且您将无法创建引用'T'的通用变量。 – 2010-01-19 16:39:06
这已被问了很多次:http://stackoverflow.com/questions/2007142/generic-class-members-in-c – JonH 2010-01-19 16:53:38