在运行时,我不知道变量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;
}
Run Code Online (Sandbox Code Playgroud)
唯一的区别在于ShellProperty<AnyType>.
因此if else,我决定使用反射来在运行时获取属性类型,而不是使用大量语句编写它:
Type t1 = v1.GetType().GetProperty("Value").PropertyType;
dynamic v2 = (v1 as ShellProperty<t1>).Value;
Run Code Online (Sandbox Code Playgroud)
此代码获取PropertyType的v1,并将其分配给本地变量t1,但在那之后,我的编译器说:
t1是一个变量但是像一个类型一样使用
所以它不允许我在t1里面写ShellProperty<>.
请告诉我如何解决这个问题,以及如何获得比我更紧凑的代码.我需要创建一个新类吗?
Dex*_*Dex 16
你非常接近,你只是错过了一个电话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);
Run Code Online (Sandbox Code Playgroud)
编辑:正如@PetSerAl指出的那样,我添加了一些不必要的间接层.对不起OP,你可能想要一个像这样的单线:
dynamic v2 = v1.GetType().GetProperty("Value").GetValue(v1, null);
Run Code Online (Sandbox Code Playgroud)
小智 12
对于泛型,您必须动态创建它们.
MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
Run Code Online (Sandbox Code Playgroud)
要创建通用对象,您可以
var type = typeof(ShellProperty<>).MakeGenericType(typeof(SomeObject));
var v2 = Activator.CreateInstance(type);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48642 次 |
| 最近记录: |