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

问题描述 投票:0回答:4

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

Type type = someObject.GetType();

foreach (PropertyInfo pi in type.GetProperties())
{
   // umm... Not sure how to tell if this property is static
}
c# reflection compact-framework
4个回答
58
投票

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

https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo


13
投票

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.