所以我做了一些实验,我发现虽然这样:
public class SelfOfT
{
// This won't compile
public class FailureOf<T> : T
{
}
}
另一方面,失败了:
public class SelfOfT
{
public interface IMyInterface
{
}
public static void Second()
{
// This works fine, and achieves the same end as what I'm trying to do with FailureOf<T>
AssemblyName name = new AssemblyName("Dynamics");
AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
ModuleBuilder modbuilder = asmBuilder.DefineDynamicModule("MyModule");
TypeBuilder typeBuild = modbuilder.DefineType("SuccessfulOf", TypeAttributes.Public);
typeBuild.AddInterfaceImplementation(typeof(IMyInterface));
var TParam = typeBuild.DefineGenericParameters(new String[] { "T" }).First();
TParam.SetGenericParameterAttributes(GenericParameterAttributes.None);
Type myType = typeBuild.CreateType();
Type genericMyType = myType.MakeGenericType(typeof(IMyInterface));
IMyInterface my = (IMyInterface)Activator.CreateInstance(genericMyType);
}
}
工作正常。如果我无论如何都可以在运行时做到这一点,那么在编译时让它可用似乎会节省很多麻烦。