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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/392122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:43:54  来源:igfitidea点击:

In C#, how can I tell if a property is static? (.Net CF 2.0)

c#reflectioncompact-framework

提问by CrashCodes

FieldInfo has an IsStatic member, but PropertyInfo doesn't. I assume I'm just overlooking what I need.

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

Type type = someObject.GetType();

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

采纳答案by Steven Behnke

To determine whether a property is static, you must obtain the MethodInfo for the get or set accessor, by calling the GetGetMethod or the GetSetMethod method, and examine its IsStatic property.

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

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

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

回答by ctacke

Why not use

为什么不使用

type.GetProperties(BindingFlags.Static)

回答by relatively_random

As an actual quick and simple solution to the question asked, you can use this:

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

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

回答by furier

Better solution

更好的解决方案

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

Usage:

用法:

property.IsStatic()