如何使用局部变量作为类型?编译器说“它是一个变量,但像类型一样使用" [英] How to use local variable as a type? Compiler says "it is a variable but is used like a type"
问题描述
在运行时,我不知道 v1
是什么类型的变量.为此,我写了很多if else
语句:
At run-time, I don't know what type of variable v1
is.
For this reason, I wrote many if else
statements:
if (v1 is ShellProperty<int?>)
{
v2 = (v1 as ShellProperty<int?>).Value;
}
else if (v1 is ShellProperty<uint?>)
{
v2 = (v1 as ShellProperty<uint?>).Value;
}
else if (v1 is ShellProperty<string>)
{
v2 = (v1 as ShellProperty<string>).Value;
}
else if (v1 is ShellProperty<object>)
{
v2 = (v1 as ShellProperty<object>).Value;
}
唯一的区别在于ShellProperty
.
因此,我决定使用反射来在运行时获取属性类型,而不是使用大量 if else
语句编写此代码:
So instead of writing this with a lot of if else
statements, I decided to use reflection to get the property type at run-time:
Type t1 = v1.GetType().GetProperty("Value").PropertyType;
dynamic v2 = (v1 as ShellProperty<t1>).Value;
这段代码获取了v1
的PropertyType
,并将其分配给了局部变量t1
,但是在那之后,我的编译器说:
This code gets the PropertyType
of v1
and assigns it to the local variable t1
, but after that, my compiler says that:
t1 是一个变量,但像类型一样使用
t1 is a variable but is used like a type
所以它不允许我在 ShellProperty<>
中写入 t1
.
So it does not allow me to write t1
inside ShellProperty<>
.
请告诉我如何解决这个问题以及如何获得比我现有的更紧凑的代码.我需要创建一个新类吗?
Please tell me how to solve this problem and how to get more compact code than what I have. Do I need to create a new class?
推荐答案
你很接近,只是错过了对 MakeGenericType
的调用.
You were very close, you were just missing a call to MakeGenericType
.
我相信您的代码如下所示:
I believe your code would look like the following:
Type t1 = v1.GetType().GetProperty("Value").PropertyType;
var shellPropertyType = typeof(ShellProperty<>);
var specificShellPropertyType = shellPropertyType.MakeGenericType(t1);
dynamic v2 = specificShellPropertyType.GetProperty("Value").GetValue(v1, null);
正如@PetSerAl 指出的那样,我添加了一些不必要的间接层.抱歉 OP,您可能想要一个像这样的衬里:
As @PetSerAl pointed out I added some layers of indirection that were unnecessary. Sorry OP, you probably want a one liner like:
dynamic v2 = v1.GetType().GetProperty("Value").GetValue(v1, null);
这篇关于如何使用局部变量作为类型?编译器说“它是一个变量,但像类型一样使用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!