GetRuntimeProperties而不是GetProperty

Jac*_*cik 5 c# reflection

我需要在泛型类型中找到属性.这是一种古老的方式(因为我的代码专用于WinRT,我相信我需要另一种方法):

PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetProperty(idField, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);  
Run Code Online (Sandbox Code Playgroud)

我需要使用相同的结果GetRuntimeProperties.这是我的方法:

PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetRuntimeProperties().Single(p => p.Name.ToUpper() == idField.ToUpper()...  
Run Code Online (Sandbox Code Playgroud)

你可以看到我IgnoreCase以自定义方式实现,可能它可以做得更好?
我该如何实施剩余的BindingFlags

谢谢!

Yuv*_*kov 6

你真的不需要.这是如何Type.GetRuntimeProperties实现的:

public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type)
{
    CheckAndThrow(type);

    IEnumerable<PropertyInfo> properties = type.GetProperties(everything);
    return properties;
}
Run Code Online (Sandbox Code Playgroud)

其中everything定义如下:

private const BindingFlags everything = BindingFlags.Instance |
                                        BindingFlags.Public | 
                                        BindingFlags.NonPublic | 
                                        BindingFlags.Static;
Run Code Online (Sandbox Code Playgroud)

这意味着它已经在寻找您需要的标志.

编辑:

如果要指定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();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这尚未经过测试.它只是试图告诉你,你可以自己做.