gpt4 book ai didi

.net - 如何通过反射获取静态属性

转载 作者:行者123 更新时间:2023-12-03 04:46:30 25 4
gpt4 key购买 nike

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

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

End Function

上面的代码对于公共(public)实例属性工作得很好,到目前为止这就是我所需要的。据说我可以使用 BindingFlags 来请求其他类型的属性(私有(private)、静态),但我似乎找不到正确的组合。

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...
}

关于.net - 如何通过反射获取静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/451453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com