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

41

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

Type type = someObject.GetType();

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

58

4
BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy 对我起了作用。 - Jonathon Reinhart

14

作为一个实际的快速简单解决方案来回答这个问题,你可以使用这个:

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

10
更好的解决方案。
public static class PropertyInfoExtensions
{
    public static bool IsStatic(this PropertyInfo source, bool nonPublic = false) 
        => source.GetAccessors(nonPublic).Any(x => x.IsStatic);
}

用法:

property.IsStatic()

8
为什么不使用?
type.GetProperties(BindingFlags.Static)

不错!但是在我的情况下,我想要非静态的,它似乎没有绑定标志。 - CrashCodes
这将不会给你getter的静态绑定标志。 - Alfredo A.
3
这不是一个有效的解决方案。首先,它甚至没有列出静态属性,因为绑定标志也应该指定访问级别(BindingFlags.PublicBindingFlags.NonPublic或两者都有)。其次,它只是列出了静态属性(输入是Type,输出是PropertyInfo[]),而问题是“给定一个属性,如何确定它是否是静态的?”(输入是PropertyInfo,输出是bool)。我猜你提议的最接近的东西就是在末尾加上.Contains(property),但我认为这将是一个次优解。 - Grx70

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接