本文介绍了如何使用局部变量作为类型?编译器说“它是一个变量,但像类型一样使用”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行时,我不知道变量 v1 是什么类型。
出于这个原因,我写了许多 if 语句:

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< AnyType>

因此,我决定使用反射来获取该属性,而不是使用很多 if 语句来编写它。在运行时键入:

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;

此代码获取 PropertyType c $ c> v1 并将其分配给局部变量 t1 ,但是在那之后,我的编译器说:

This code gets the PropertyType of v1 and assigns it to the local variable t1, but after that, my compiler says that:

不允许我在 ShellProperty<> 内写 t1

请告诉我如何解决此问题以及如何获得比我现有的紧凑的代码。我需要创建一个新班吗?

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

这篇关于如何使用局部变量作为类型?编译器说“它是一个变量,但像类型一样使用”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:00