代码之家  ›  专栏  ›  技术社区  ›  CrashCodes

在C中,如何判断属性是否是静态的?(.NET CF 2)

  •  24
  • CrashCodes  · 技术社区  · 17 年前

    FieldInfo有一个静态成员,但PropertyInfo没有。我想我只是忽略了我需要的。

    Type type = someObject.GetType();
    
    foreach (PropertyInfo pi in type.GetProperties())
    {
       // umm... Not sure how to tell if this property is static
    }
    
    4 回复  |  直到 7 年前
        1
  •  38
  •   Steven Behnke    17 年前

    若要确定属性是静态的,必须通过调用get get method或get set method方法来获取get或set访问器的MethodInfo,并检查其IsStatic属性。

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

        2
  •  10
  •   dove    16 年前

    为什么不使用

    type.GetProperties(BindingFlags.Static)
    
        3
  •  3
  •   furier    8 年前

    较好的解决方案

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

    用途:

    property.IsStatic()
    
        4
  •  3
  •   relatively_random    7 年前

    作为对所问问题的快速简单的实际解决方案,您可以使用以下方法:

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