在C#中,如何判断属性是否为静态? (.Net CF 2.0)
FieldInfo有一个IsStatic成员,但PropertyInfo没有。 我想我只是忽略了我需要的东西。
Type type = someObject.GetType(); foreach (PropertyInfo pi in type.GetProperties()) { // umm... Not sure how to tell if this property is static }
要确定属性是否为静态,必须通过调用GetGetMethod或GetSetMethod方法获取get或set访问器的MethodInfo,并检查其IsStatic属性。
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx
为什么不用
type.GetProperties(BindingFlags.Static)
作为问题的实际快速简单的解决方案,您可以使用:
property.GetAccessors(true)[0].IsStatic;
更好的方案
public static class PropertyInfoExtensions { public static bool IsStatic(this PropertyInfo source, bool nonPublic = false) => source.GetAccessors(nonPublic).Any(x => x.IsStatic); }
用法:
property.IsStatic()