如何使用反射获取静态属性 [英] How to get a Static property with Reflection

查看:33
本文介绍了如何使用反射获取静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这看起来很基本,但我无法让它工作.我有一个对象,我正在使用反射来获取它的公共属性.这些属性之一是静态的,我没有运气得到它.

So this seems pretty basic but I can't get it to work. I have an Object, and I am using reflection to get to it's public properties. One of these properties is static and I'm having no luck getting to it.

Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
    Return obj.GetType.GetProperty(propName)

End Function

以上代码适用于公共实例属性,到目前为止,我只需要这些.据说我可以使用 BindingFlags 来请求其他类型的属性(私有、静态),但我似乎找不到正确的组合.

The above code works fine for Public Instance properties, which up until now is all that I have needed. Supposedly I can use BindingFlags to request other types of properties (private, static), but I can't seem to find the right combination.

Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo
    Return obj.GetType.GetProperty(propName, Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public)

End Function

但是,请求任何静态成员都不会返回任何内容..NET 反射器可以很好地看到静态属性,所以很明显我在这里遗漏了一些东西.

But still, requesting any Static members return nothing. .NET reflector can see the static properties just fine, so clearly I am missing something here.

推荐答案

好的,所以我的关键是使用 .FlattenHierarchy BindingFlag.我真的不知道为什么我只是凭直觉添加它并开始工作.因此,允许我获取公共实例或静态属性的最终解决方案是:

Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
  Reflection.BindingFlags.FlattenHierarchy)

这篇关于如何使用反射获取静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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