使用字符串值通过反射设置属性 [英] Setting a property by reflection with a string value

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

问题描述

我想通过反射设置一个对象的属性,值为 string 类型.因此,例如,假设我有一个 Ship 类,其属性为 Latitude,它是一个 double.

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:

As is, this throws an 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 类型的运行时信息来更改表示格式.但是,并非所有转换都是可能的,如果您想支持来自非 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.

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

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天全站免登陆