我想通过反射设置一个对象的属性,值类型为字符串。 例如,假设我有一个Ship类,它的纬度属性是double。

这是我想做的:

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

这将抛出一个ArgumentException:

类型为System的对象。字符串'不能转换为'System.Double'类型。

如何将值转换为适当的类型,基于propertyInfo?


当前回答

你可能在找皈依者。ChangeType功能。例如:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

其他回答

我注意到很多人都推荐Convert。ChangeType -这在某些情况下确实有效,但是一旦你开始涉及可空类型,你就会开始收到InvalidCastExceptions:

http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx

几年前编写了一个包装器来处理这个问题,但这也不是完美的。

http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx

你可能在找皈依者。ChangeType功能。例如:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

正如其他几个人所说,您希望使用Convert。ChangeType:

propertyInfo.SetValue(ship,
    Convert.ChangeType(value, propertyInfo.PropertyType),
    null);

事实上,我建议您查看整个Convert Class。

这个类和许多其他有用的类都是系统名称空间的一部分。我发现,大约每隔一年扫描一下这个名称空间,看看我遗漏了哪些特性,这很有用。试试吧!

我将用一个一般的答案来回答这个问题。通常这些答案不工作与指导。这是一个工作版本与guids。

var stringVal="6e3ba183-89d9-e611-80c2-00155dcfb231"; // guid value as string to set
var prop = obj.GetType().GetProperty("FooGuidProperty"); // property to be setted
var propType = prop.PropertyType;

// var will be type of guid here
var valWithRealType = TypeDescriptor.GetConverter(propType).ConvertFrom(stringVal); 

您是想玩玩Reflection还是想构建一个软件产品?我想问你为什么要用反射来设置属性。

Double new_latitude;

Double.TryParse (value, out new_latitude);
ship.Latitude = new_latitude;