当一些可能是通用的时,迭代嵌套属性

时间:2012-05-02 23:01:44

标签: c# generics reflection

public class MyContext: DbContext
{
    public MyContext() : base("VidallyEF") {}

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<Contest> Contests { get; set; }
    public DbSet<Comment> Comments { get; set; }
    public DbSet<Submission> Submissions { get; set; }
}

我正在尝试遍历MyContext的属性,然后遍历每个属性的属性。我有这个:

foreach (var table in typeof(MyContext).GetProperties())
            {
                // TODO add check that table is DbSet<TEntity>..not sure..

                PropertyInfo[] info = table.GetType().GetProperties();

                foreach (var propertyInfo in info)
                {
                    //Loop 
                    foreach (var attribute in propertyInfo.GetCustomAttributes(false))
                    {
                        if (attribute is MyAttribute)
                        {
                           //do stuff
                        }
                    }
                }        

            }

问题是因为MyContext的属性是泛型,GetType()。GetProperties()不返回底层对象的属性。我需要了解User和Role对象。

任何帮助将不胜感激,

由于

1 个答案:

答案 0 :(得分:3)

PropertyInfo上有一些可用的东西会有所帮助。 IsGenericType将告诉您属性类型是否为通用属性,GetGenericArguments()调用将返回包含泛型类型参数类型的Type数组。

foreach (var property in someInstance.GetType().GetProperties())
{
    if (property.PropertyType.IsGenericType)
    {
        var genericArguments = property.PropertyType.GetGenericArguments();
        //Do something with the generic parameter types                
    }
}

同样重要的是要注意GetProperties()仅返回指定类型的可用属性。如果你想要包含或使用你指定类型的类型,你将不得不做一些挖掘来获得它们。

相关问题