如何使用局部变量作为类型?编译器说 "it is a variable but is used like a type"

How to use local variable as a type? Compiler says "it is a variable but is used like a type"

在运行时,我不知道变量v1是什么类型。 为此,我写了很多if else个语句:

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>

因此,我决定在 运行-time:

使用反射来获取 属性 类型,而不是使用大量 if else 语句来编写此代码:

 Type t1 = v1.GetType().GetProperty("Value").PropertyType;
 dynamic v2 = (v1 as ShellProperty<t1>).Value;

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

t1 is a variable but is used like a type

所以它不允许我在ShellProperty<>里面写t1

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

对于泛型,您必须动态创建它们。

MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

要创建通用对象,您可以

var type = typeof(ShellProperty<>).MakeGenericType(typeof(SomeObject));
var v2 = Activator.CreateInstance(type);

请参考Initializing a Generic variable from a C# Type Variable

你非常接近,只是错过了给 MakeGenericType 的电话。

我相信您的代码如下所示:

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,你可能想要一个像这样的单衬垫:

dynamic v2 = v1.GetType().GetProperty("Value").GetValue(v1, null);