在C#3.5中是否有一种方法可以使用反射来设置对象属性?
例如:
MyObject obj = new MyObject();
obj.Name = "Value";
我想obj.Name用反思来设定.就像是:
Reflection.SetProperty(obj, "Name") = "Value";
有办法做到这一点吗?
我想通过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);
这样就抛出了ArgumentException:
"System.String"类型的对象无法转换为"System.Double"类型.
如何将值转换为正确的类型,基于propertyInfo?