In C#, how can I tell if a property is static? (.Net CF 2.0)

给你一囗甜甜゛ 提交于 2019-12-09 14:01:51

问题


FieldInfo has an IsStatic member, but PropertyInfo doesn't. I assume I'm just overlooking what I need.

Type type = someObject.GetType();

foreach (PropertyInfo pi in type.GetProperties())
{
   // umm... Not sure how to tell if this property is static
}

回答1:


To determine whether a property is static, you must obtain the MethodInfo for the get or set accessor, by calling the GetGetMethod or the GetSetMethod method, and examine its IsStatic property.

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx




回答2:


Why not use

type.GetProperties(BindingFlags.Static)



回答3:


Better solution

public static class PropertyInfoExtensions
{
    public static bool IsStatic(this PropertyInfo source, bool nonPublic = false) 
        => source.GetAccessors(nonPublic).Any(x => x.IsStatic);
}

Usage:

property.IsStatic()



回答4:


As an actual quick and simple solution to the question asked, you can use this:

propertyInfo.GetAccessors(true)[0].IsStatic;


来源:https://stackoverflow.com/questions/392122/in-c-how-can-i-tell-if-a-property-is-static-net-cf-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!