如何使用Reflection获取静态属性

Cor*_*nie 104 .net reflection static

所以这看起来非常基本,但我无法让它发挥作用.我有一个Object,我使用反射来获取它的公共属性.其中一个属性是静态的,我没有运气.

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

End Function
Run Code Online (Sandbox Code Playgroud)

上面的代码适用于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
Run Code Online (Sandbox Code Playgroud)

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

小智 123

或者看看这个...

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...
}
Run Code Online (Sandbox Code Playgroud)

  • `p.GetValue(null);`也有效.第二个"null"不是必需的. (7认同)
  • 这两个空值对应哪些变量?如果可能,您将如何使用命名参数编写此代码?谢谢。 (2认同)

ear*_*ess 41

这是C#,但应该给你一个想法:

public static void Main() {
    typeof(Program).GetProperty("GetMe", BindingFlags.NonPublic | BindingFlags.Static);
}

private static int GetMe {
    get { return 0; }
}
Run Code Online (Sandbox Code Playgroud)

(您只需要OR NonPublic和Static)

  • 在我的情况下,仅使用这两个标志不起作用.我还必须使用.FlattenHierarchy标志. (3认同)
  • @CoreyDownie同意。`BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy`是唯一对我有用的东西。 (3认同)

小智 35

有点清晰......

// 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;
Run Code Online (Sandbox Code Playgroud)


Cor*_*nie 28

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

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
  Reflection.BindingFlags.FlattenHierarchy)
Run Code Online (Sandbox Code Playgroud)


Igo*_*gor 7

myType.GetProperties(BindingFlags.Public | BindingFlags.Static |  BindingFlags.FlattenHierarchy);
Run Code Online (Sandbox Code Playgroud)

这将返回静态基类或特定类型中的所有静态属性,也可能返回子项.