简体   繁体   中英

Why can I inherit from a generic type at runtime, but not compile time?

So I was doing some experimenting, and I found that while this:

public class SelfOfT
{
    // This won't compile
    public class FailureOf<T> : T
    {

    }
}

fails, this, on the other hand:

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);

    }
}

works fine. It seems like it would save a lot of trouble to just make this available at compile time if I can do it at runtime anyway.

Uhm, you're not allowed to do that at runtime either.

Note that in your case, you're not specifying the class to inherit from.

To do that, you need to use one of the overloads to DefineType that takes a Type parameter to inherit from.

However, at runtime, you're not allowed to specify T either for that parameter, you would have to specify a specific type, which would be no difference from compile time.

Your code that uses reflection actually defines this:

public class SuccessfulOf<T> : IMyInterface
{

}

You cannot do what you want ( class FailureOf<T> : T ) because the base type T must be known at compile-time. At run-time with reflection you can still not do it, since T must be known.

Because in the second code you are declaring the type public class FailureOf<T> : IMyInterface , not public class FailureOf<T> : T .

Even if you declare the generic type in the surrounding class, you still can't inherit from it because you can't inherit a type parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM