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

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

我希望通过反射设置对象的属性,其值为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?


ABOUTYOU
浏览 640回答 3
3回答

芜湖不芜

就像其他几个人说的,您想要使用Convert.ChangeType:propertyInfo.SetValue(ship,     Convert.ChangeType(value, propertyInfo.PropertyType),     null);事实上,我建议你看看Convert班级,等级.类和许多其他有用的类是System命名空间..我发现每年大约扫描这个名称空间,看看我遗漏了哪些特性是有用的。试试看!
打开App,查看更多内容
随时随地看视频慕课网APP