FieldInfo 有 IsStatic 成员,但 PropertyInfo 没有。我想我只是忽略了我需要的东西。
Type type = someObject.GetType();
foreach (PropertyInfo pi in type.GetProperties())
{
// umm... Not sure how to tell if this property is static
}
要确定属性是否静态,您必须通过调用 GetGetMethod 或 GetSetMethod 方法获取 get 或 set 访问器的 MethodInfo,并检查其 IsStatic 属性。
https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo
作为所提问题的实际快速且简单的解决方案,您可以使用以下方法:
propertyInfo.GetAccessors(nonPublic: true)[0].IsStatic;
更好的解决方案
public static class PropertyInfoExtensions
{
public static bool IsStatic(this PropertyInfo source, bool nonPublic = false)
=> source.GetAccessors(nonPublic).Any(x => x.IsStatic);
}
用途:
property.IsStatic()
为什么不使用
type.GetProperties(BindingFlags.Static)