简体   繁体   English

C#类型或名称空间预期混乱

[英]C# type or namespace expected confusion

Im getting slightly confused by a C# error. 我被C#错误弄糊涂了。

Type t = thing.GetType()

t is now a type. t现在是一种类型。 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. t是在运行时创建的Type对象。 Generics expect a type name, resolved at compile time. 泛型期望一个类型名称,该名称在编译时解析。 To create a generic at runtime, you have to use MakeGenericType 要在运行时创建泛型,必须使用MakeGenericType

For example: 例如:

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

t is an object instance of type Type , ie something that only exists at runtime. t是类型Type的对象实例,即仅在运行时才存在的对象。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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