如何获得与反射的静态属性静态、反射、如何获得、属性

2023-09-02 20:43:42 作者:画个句号给今天

因此​​,这似乎是pretty的基本的,但我不能得到它的工作。我有一个对象,我使用反射来得到它的公共属性。其中一个属性是静态的,我有没有运气得到它。

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

以上code正常工作的公共实例属性,直到现在都是我所需要的。按说我可以使用的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)