typeof(T) may return null

2020-02-01 04:31发布

问题:

When using the typeof operator on type created through TypeBuilder, the operator will return null.

I'm curious why this happens and how to prevent it.


I'm starting to think this is a VS bug in the immediate window, but I'm not quite sure. It's very easy to blame others first.

Ok... code to reproduce issue:

    static void Main()
    {
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
            new AssemblyName("MyAssembly"),
            AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule");
        TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public, typeof(ArrayList));

        ArrayList o = (ArrayList)Activator.CreateInstance(typeBuilder.CreateType());

        Console.WriteLine(o.GetType().Name);
    }

If you put a breakpoint after the variable o and type typeof(MyType) in the VS Immediate Windows you'll get the issue.

回答1:

When using the typeof operator on type created through TypeBuilder, the operator will return null.

First of all, the claim is correct. If you write this program and then stop it in the debugger and say "typeof(MyType)" in the immediate window, the result that comes back is "null".

I'm curious why this happens

Beats the heck out of me. If I had to guess, I'd say that maybe the expression evaluator is communicating with the CLR's debugging subsystem to try and get a metadata token for the type by its name, and the CLR is returning some garbage nil token rather than producing an error.

I hasten to emphasize that this is a guess; I have not actually debugged it.

I'm starting to think this is a VS bug in the immediate window

That seems likely. The correct thing that it should be doing is giving the error "the type or namespace 'MyType' is not valid in this scope". The bug will almost certainly be in the C# runtime expression evaluator, not in the immediate window itself.

Thanks for bringing the issue to my attention. I'll file a bug with the expression evaluator maintainers and we'll see if they can address the issue.

how to prevent it?

If it hurts when you type "typeof(MyType)" then stop typing that.



回答2:

If you put a breakpoint after the variable 'o' and type typeof(MyType) in the VS Immediate Windows you'll get the issue.

Well, yeah. MyType doesn't have a symbol (you're defining it using reflection!), so you can't use typeof on it.

Edit: For clarification, there is exactly one time where you can use typeof and get a runtime-created type: When you're using generics.

Type MyMethod<T>() where T : class {
    return typeof(T);
}

Type myType = //create type dynamically;

Type myOtherType = //invoke MyMethod with myType as the type parameter

Debug.Assert(myType == myOtherType); //will not fire


标签: c# clr clr4.0