我想通过反射设置一个对象的属性,值类型为字符串。 例如,假设我有一个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?


当前回答

我尝试了LBushkin的答案,它工作得很好,但它不适用于空值和可空字段。所以我把它改成这样:

propertyName= "Latitude";
PropertyInfo propertyInfo = ship.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
     Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
     object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
     propertyInfo.SetValue(ship, safeValue, null);
}

其他回答

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

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

我尝试了LBushkin的答案,它工作得很好,但它不适用于空值和可空字段。所以我把它改成这样:

propertyName= "Latitude";
PropertyInfo propertyInfo = ship.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
     Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
     object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
     propertyInfo.SetValue(ship, safeValue, null);
}

我将用一个一般的答案来回答这个问题。通常这些答案不工作与指导。这是一个工作版本与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); 

或者你可以试试:

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

//But this will cause problems if your string value IsNullOrEmplty...

你可以使用Convert.ChangeType() -它允许你在任何IConvertible类型上使用运行时信息来更改表示格式。但是,并不是所有的转换都是可能的,如果您希望支持从非IConvertible类型转换,则可能需要编写特殊情况的逻辑。

相应的代码(没有异常处理或特殊情况逻辑)将是:

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