首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >GetRuntimeProperties而不是GetProperty

GetRuntimeProperties而不是GetProperty
EN

Stack Overflow用户
提问于 2015-01-12 12:29:37
回答 1查看 7.5K关注 0票数 6

我需要在泛型类型中找到属性。这是一种古老的方法(由于我的代码是专门为WinRT编写的,我认为我需要另一种方法):

代码语言:javascript
运行
复制
PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetProperty(idField, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);  

我需要使用GetRuntimeProperties实现同样的结果。这是我的方法:

代码语言:javascript
运行
复制
PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetRuntimeProperties().Single(p => p.Name.ToUpper() == idField.ToUpper()...  

正如您所看到的,我以自定义的方式实现了IgnoreCase,它可能会做得更好吗?

如何实现剩余的BindingFlags

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-12 12:40:40

你其实不需要。Type.GetRuntimeProperties是这样实现的:

代码语言:javascript
运行
复制
public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type)
{
    CheckAndThrow(type);

    IEnumerable<PropertyInfo> properties = type.GetProperties(everything);
    return properties;
}

其中everything的定义如下:

代码语言:javascript
运行
复制
private const BindingFlags everything = BindingFlags.Instance |
                                        BindingFlags.Public | 
                                        BindingFlags.NonPublic | 
                                        BindingFlags.Static;

这意味着它将已经查找所需的标志。

编辑:

如果要自己指定BindingFlags,可以编写自己的自定义扩展方法:

代码语言:javascript
运行
复制
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();
    }
}

注意,这个还没有经过测试。这只不过是试图向你展示你自己能做到的。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27902082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档