如何通过反射从基本类型获取静态属性
我尝试通过反射从基本类型中获取静态属性。在这方面,有关此主题有很多问题,但它们都专注于从目标类型中获取基本类型或静态属性的非静态属性。
public class A
{
public static string STATIC_BaseProp => "STATIC_BaseProp"; //<-- I want this
public string BaseProp => "BaseProp";
}
public class B : A
{
public static string STATIC_Prop => "STATIC_Prop";
public string Prop => "PROP";
}
static void Main(string[] args)
{
var type = typeof(B);
foreach (var propertyInfo in type.GetProperties())
{
Console.log(propertyInfo);
}
}
输出:
System.String STATIC_Prop
System.String Prop
System.String BaseProp
这似乎仅适应目标类型的静态特性以及目标类型和基本类型的非静态特性。但是我只想要基本类型的静态属性( static_baseprop
)
有人知道该怎么做吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要仅获取基本类型的静态属性,我建议访问 type.basetype 属性(如公共|静态
免责声明:这仅适用于继承层次结构的一个级别。如果您想要更深入的见解,则需要深入研究基质。
输出:
如果您想要整个继承层次结构中的所有静态属性,则可以使用这种bindingfalgs的组合:
如果您在
a
a 上添加父类,则可以删除它也可以工作。输出:
To get only the static properties of the base type I would suggest to access the Type.BaseType property (like described in this answer) and use only
Public | Static
Bindingflags:disclaimer: this works only for one level of the inheritance hierarchy. You would need to dive through the basetypes if you want deeper insights.
Output:
If you want all static properties throughout the entire inheritance hierarchy you can use this combination of BindingFalgs:
Here is an example to demostrate that it works also if you add a parent class on top of
A
Output: