简体   繁体   中英

C# type or namespace expected confusion

Im getting slightly confused by a C# error.

Type t = thing.GetType()

t is now a type. but if i attempt to do this:

new GenericThing<t>

I get a warning saying type or namespace expected. What am i missing?

t is a Type object created at runtime. Generics expect a type name, resolved at compile time. To create a generic at runtime, you have to use MakeGenericType

For example:

Activator.CreateInstance(typeof(GenericThing<>).MakeGenericType(t));

t is an object instance of type Type , ie something that only exists at runtime. Generics work at compile time and expect the name of the type.

I think you agree that the following doesn't make sense:

Type t = thing.GetType()
TypeOfThing instance = new t();

And for the same reason, you can't pass a type instance as the parameter of a generic.

Type代表一个类型,而不是实际上一个,所以你不能使用实例的类Type在期望一个类型或类型参数的地方。

you should do something like this :

var youGeneric = typeof(GenericThing<>).MakeGenericType(t)
                                       .GetConstructor(Type.EmptyTypes)
                                       .Invoke(null);

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