我需要在泛型类型中找到属性。这是一种古老的方法(由于我的代码是专门为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
?
谢谢!
发布于 2015-01-12 12:40:40
你其实不需要。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();
}
}
注意,这个还没有经过测试。这只不过是试图向你展示你自己能做到的。
https://stackoverflow.com/questions/27902082
复制相似问题