相关疑难解决方法(0)

使用反射设置对象属性

在C#3.5中是否有一种方法可以使用反射来设置对象属性?

例如:

MyObject obj = new MyObject();
obj.Name = "Value";
Run Code Online (Sandbox Code Playgroud)

我想obj.Name用反思来设定.就像是:

Reflection.SetProperty(obj, "Name") = "Value";
Run Code Online (Sandbox Code Playgroud)

有办法做到这一点吗?

.net c# reflection properties

308
推荐指数
8
解决办法
24万
查看次数

通过反射使用字符串值设置属性

我想通过Reflection设置对象的属性,值为type string.所以,举个例子,假设我有Ship一个属性为的类Latitude,它是一个double.

这是我想做的事情:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null);
Run Code Online (Sandbox Code Playgroud)

这样就抛出了ArgumentException:

"System.String"类型的对象无法转换为"System.Double"类型.

如何将值转换为正确的类型,基于propertyInfo

c# reflection type-conversion propertyinfo setvalue

298
推荐指数
8
解决办法
26万
查看次数