在C#中,如何判断属性是否为静态?(.Net CF 2.0)

Cra*_*des 28 c# reflection compact-framework

FieldInfo有一个IsStatic成员,但PropertyInfo没有.我想我只是忽略了我需要的东西.

Type type = someObject.GetType();

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

Ste*_*nke 42

要确定属性是否为静态,必须通过调用GetGetMethod或GetSetMethod方法获取get或set访问器的MethodInfo,并检查其IsStatic属性.

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

  • `BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy`为我工作. (3认同)

cta*_*cke 9

为什么不用

type.GetProperties(BindingFlags.Static)
Run Code Online (Sandbox Code Playgroud)

  • BindingFlags.Instance (9认同)
  • 这不是一个有效的解决方案。首先,它甚至没有列出静态属性,因为绑定标志还应该指定访问级别(“BindingFlags.Public”、“BindingFlags.NonPublic”或两者)。其次,这只是列出静态属性(输入是“Type”,输出是“PropertyInfo[]”),而问题是“给定一个属性,如何确定它是否是静态的?” (输入是“PropertyInfo”,输出是“bool”)。我想最接近你的建议的是在最后加上“.Contains(property)”,但我认为这将是一个次优的解决方案。 (3认同)

rel*_*dom 6

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

propertyInfo.GetAccessors(true)[0].IsStatic;
Run Code Online (Sandbox Code Playgroud)


fur*_*ier 6

更好的解决方案

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

用法:

property.IsStatic()
Run Code Online (Sandbox Code Playgroud)