尝试使用反射来查找类的第一个 Int32 属性
我正在尝试找到类的第一个属性,它是一个Integer
..并获取它的值。
所以我有以下代码..它总是返回 false:
foreach(var property in type.GetProperties(BindingFlags.Public |
BindingFlags.Instance))
{
var someType = property.PropertyType is int; // Always false.
}
为什么这是/我做错了什么。这应该很简单:(
/我今天过得很糟糕......
I'm trying to find the first property of a class that is an Integer
.. and get it's value.
So i've got the following code .. which always returns false:
foreach(var property in type.GetProperties(BindingFlags.Public |
BindingFlags.Instance))
{
var someType = property.PropertyType is int; // Always false.
}
Why is this / what did I do wrong. This should be really simple :(
/me is having a bad day ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将测试更改为:
这是必要的,因为属性的属性类型本身不是整数:它是一个(松散地)表示属性类型的
System.Type
对象-getter 返回/ property-setter 接受。另一方面,在包含类型的实例上调用属性 getter 将产生一个实际的整数。下面是使用 LINQ 代替
foreach
循环的方法:(如果不存在这样的属性,这将引发异常。)
从包含类型的实例中检索属性的值:
这将如果“第一个”
Int32
属性恰好是一个索引器,或者实际上它根本没有 getter,那么当然会失败。如果可能出现这种情况,您可以在原始查询中过滤掉此类属性。另请注意,此代码的用途有限,因为“类的第一个属性是整数”的想法有点可疑。来自
Type.GetProperties
:Change the test to:
This is necessary because the property's property-type is itself not an integer: it is a
System.Type
object that (loosely) represents what type the property-getter returns / property-setter accepts. On the other hand, invoking the property getter on an instance of the containing-type will produce an actual integer.Here's a way to use LINQ instead of the
foreach
loop:(This will throw an exception if no such property exists.)
To retrieve the value of the property from an instance of the containing type:
This will of course fail if the 'first'
Int32
property happens to be an indexer or indeed if it simply doesn't have a getter. You could filter such properties out on the original query if such scenarios are likely.Also note that this code is of limited use because the idea of 'the first property of a class that is an integer' is a little bit suspect. From
Type.GetProperties
: