设置反射属性具有字符串值 [英] Setting a property by reflection with a string value

查看:175
本文介绍了设置反射属性具有字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过反射来设置对象的属性,类型字符串的值。
所以,举例来说,假设我有一个船舶类,以纬度的一个属性,它是一个双击

I'd like to set a property of an object through Reflection, with a value of type string. So, for instance, suppose I have a Ship class, with a property of Latitude, which is a 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。

Object of type 'System.String' cannot be converted to type 'System.Double'.

我怎么可以转换价值为适当的类型,根据的PropertyInfo

How can I convert value to the proper type, based on propertyInfo?

推荐答案

您可以使用 Convert.ChangeType() - 它允许你使用任何 IConvertible 键入改再presentation运行时信息格式。并非所有的转换是可能的,虽然,你可能需要编写特殊情况的逻辑,如果你想从不在 IConvertible

You can use Convert.ChangeType() - It allows you to use runtime information on any IConvertible type to change representation formats. Not all conversions are possible, though, and you may need to write special case logic if you want to support conversions from types that are not IConvertible.

相应的code(不带异常处理或特殊情况下,逻辑)将是:

The corresponding code (without exception handling or special case logic) would be:

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

这篇关于设置反射属性具有字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆