[英]Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'System.IConvertible'
I am having issues with the following code. 我的以下代码有问题。 I am iterating through a set to see if an object has a certain property type and if so, do some conversion to it.
我正在遍历一个集合,以查看对象是否具有某种属性类型,如果是,则对其进行一些转换。
var props = obj.GetType().GetProperties();
foreach (var p in props)
{
if (p.PropertyType == typeof(System.Boolean))
{
var conv = Convert.ToByte(p);
}
}
I get the following error when I try to run it: 尝试运行它时出现以下错误:
"Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'System.IConvertible'." “无法将类型为'System.Reflection.RuntimePropertyInfo'的对象强制转换为类型为'System.IConvertible'。”
I assume you want to get the value of the property and convert that to a byte, right? 我假设你想要得到的财产的价值,将其转换成一个字节,对不对? Not the property itself... so:
不是财产本身...所以:
var conv = Convert.ToByte(p.GetValue(obj, null));
It seems odd to have it as a byte
rather than a bool
, admittedly... I'd have expected: 坦率地说,将其作为
byte
而不是bool
似乎很奇怪……我曾期望:
var conv = (bool) p.GetValue(obj, null);
I'd also personally use: 我还亲自使用:
if (p.PropertyType == typeof(bool))
rather than spelling out the System.Boolean
explicitly. 而不是明确拼写
System.Boolean
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.