Can I declare a variable of Type<T> without specifying T at compile time? [duplicate]
Possible Duplicate:
Can I declare a variable of Type<T> without specifying T at compile time?
Objective: To Load the class "MyContent" dynamically. I have 1 interface<T>
, 1 abstract generic class<T>
.
Code:
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 }
}
Now, we load:
IMyO开发者_如何学PythonbjectInterface obj = (IMyObjectInterface)Assembly.Load("MyAssembly").CreateInstance("MyObject");
IMyContentInterface<???> content = (IMyContentInterface<???>)Assembly.Load("MyAssembly").CreateInstance("MyContent");
content.MyMethod();
How to load ???
In order to call MyMethod, you would either have to include it as part of a non-generic interface or class, or call it using reflection on the object you get back (so can get the type of T at runtime)
You can only do that if you're inside a generic method or type, so that you can use a generic type. At instantination time (even if it is runtime), the exact type must be known, since .NET does not use erasure as Java does.
However, you can create an instance of any type (also generic if you use MakeGenericType
) via Activator
and assign it to a variable of the type object
.
To get the type to activate, you can get a concrete type like this this:
typeof(IMyContentInterface<>).MakeGenericType(typeToUse)
精彩评论