所以这看起来非常基本,但我无法让它发挥作用.我有一个Object,我使用反射来获取它的公共属性.其中一个属性是静态的,我没有运气.
Public Function GetProp(ByRef obj As Object, ByVal propName as String) as PropertyInfo Return obj.GetType.GetProperty(propName) End Function
上面的代码适用于Public Instance属性,到目前为止我只需要它.据说我可以使用BindingFlags来请求其他类型的属性(私有,静态),但我似乎找不到合适的组合.
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反射器可以很好地看到静态属性,所以很明显我在这里遗漏了一些东西.
或者看看这个...
Type type = typeof(MyClass); // MyClass is static class with static properties foreach (var p in type.GetProperties()) { var v = p.GetValue(null, null); // static classes cannot be instanced, so use null... }
这是C#,但应该给你一个想法:
public static void Main() { typeof(Program).GetProperty("GetMe", BindingFlags.NonPublic | BindingFlags.Static); } private static int GetMe { get { return 0; } }
(您只需要OR NonPublic和Static)
有点清晰......
// Get a PropertyInfo of specific property type(T).GetProperty(....) PropertyInfo propertyInfo; propertyInfo = typeof(TypeWithTheStaticProperty) .GetProperty("NameOfStaticProperty", BindingFlags.Public | BindingFlags.Static); // Use the PropertyInfo to retrieve the value from the type by not passing in an instance object value = propertyInfo.GetValue(null, null); // Cast the value to the desired type ExpectedType typedValue = (ExpectedType) value;
好的,所以我的关键是使用.FlattenHierarchy BindingFlag.我真的不知道为什么我只是在预感中添加它并开始工作.因此,允许我获取公共实例或静态属性的最终解决方案是:
obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _ Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _ Reflection.BindingFlags.FlattenHierarchy)
myType.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
这将返回静态基类或特定类型中的所有静态属性,也可能返回子项.