GetRuntimeProperties 而不是 GetProperty
GetRuntimeProperties instead of GetProperty
我需要在通用类型中找到 属性。这是一种旧方法(因为我的代码专用于 WinRT,所以我相信我需要另一种方法):
PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetProperty(idField, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
我需要使用 GetRuntimeProperties
获得相同的结果。这是我的方法:
PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetRuntimeProperties().Single(p => p.Name.ToUpper() == idField.ToUpper()...
如您所见,我以自定义方式实现了 IgnoreCase
,也许可以做得更好?
如何实现剩余的 BindingFlags
?
谢谢!
你其实不需要。 Type.GetRuntimeProperties
是这样实现的:
public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type)
{
CheckAndThrow(type);
IEnumerable<PropertyInfo> properties = type.GetProperties(everything);
return properties;
}
其中everything
定义如下:
private const BindingFlags everything = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static;
这意味着它已经在寻找您需要的标志。
编辑:
如果要自己指定BindingFlags
,可以自己写自定义扩展方法:
public static class TypeExtensions
{
public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo type,
BindingFlags bindingFlags)
{
var propertyInfos = type.GetProperties(bindingFlags);
var subtype = type.BaseType;
if (subtype != null)
list.AddRange(subtype.GetTypeInfo().GetAllProperties(bindingFlags));
return propertyInfos.ToArray();
}
}
注意这个还没有经过测试。这只是向您展示您可以自己完成的尝试。
我需要在通用类型中找到 属性。这是一种旧方法(因为我的代码专用于 WinRT,所以我相信我需要另一种方法):
PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetProperty(idField, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
我需要使用 GetRuntimeProperties
获得相同的结果。这是我的方法:
PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetRuntimeProperties().Single(p => p.Name.ToUpper() == idField.ToUpper()...
如您所见,我以自定义方式实现了 IgnoreCase
,也许可以做得更好?
如何实现剩余的 BindingFlags
?
谢谢!
你其实不需要。 Type.GetRuntimeProperties
是这样实现的:
public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type)
{
CheckAndThrow(type);
IEnumerable<PropertyInfo> properties = type.GetProperties(everything);
return properties;
}
其中everything
定义如下:
private const BindingFlags everything = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static;
这意味着它已经在寻找您需要的标志。
编辑:
如果要自己指定BindingFlags
,可以自己写自定义扩展方法:
public static class TypeExtensions
{
public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo type,
BindingFlags bindingFlags)
{
var propertyInfos = type.GetProperties(bindingFlags);
var subtype = type.BaseType;
if (subtype != null)
list.AddRange(subtype.GetTypeInfo().GetAllProperties(bindingFlags));
return propertyInfos.ToArray();
}
}
注意这个还没有经过测试。这只是向您展示您可以自己完成的尝试。