【问题标题】:c# how to get list of derived class properties by reflection, ordered by base class properties first, and then derived class propsc#如何通过反射获取派生类属性列表,先按基类属性排序,再按派生类props
【发布时间】:2019-03-09 18:49:36
【问题描述】:

我希望从派生类中获取属性列表 我写了一个函数,给我一个属性列表。 我的问题是我希望属性列表包含基类的第一个属性和派生类的属性 我怎样才能做到这一点?现在我得到了派生的第一个属性,然后是基数

PropertyInfo[] props = typeof(T).GetProperties();
        Dictionary<string, ColumnInfo> _colsDict = new Dictionary<string, ColumnInfo>();

        foreach (PropertyInfo prop in props)
        {
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                ColumnInfo colInfoAttr = attr as ColumnInfo;
                if (colInfoAttr != null)
                {
                    string propName = prop.Name;
                    _colsDict.Add(propName, colInfoAttr);                        
                }
            }
        }

【问题讨论】:

  • 嗯...我认为您需要先提取基类,获取它的属性并添加其余部分。意识到;属性可以是“新的”,基类可以有一个基类。
  • 提取基类字段后如何提取派生类的剩余字段?
  • Reverse()方法
  • 但这将恢复我的所有属性,我不希望基类首先按其顺序出现,然后按其顺序派生字段
  • 我可能错过了重点。如果BaseType存在,你不能使用Type.BaseType来获取基类并从中获取属性吗?

标签: c# inheritance reflection properties derived-class


【解决方案1】:

如果您知道基类类型,您可能可以这样做:

  public static Dictionary<string, object> GetProperties<Derived, Base>()
  {
        var onlyInterestedInTypes = new[] { typeof(Derived).Name, typeof(Base).Name };

        return Assembly
            .GetAssembly(typeof(Derived))
            .GetTypes()
            .Where(x => onlyInterestedInTypes.Contains(x.Name))
            .OrderBy(x => x.IsSubclassOf(typeof(Base)))
            .SelectMany(x => x.GetProperties())
            .GroupBy(x => x.Name)
            .Select(x => x.First())
            .ToDictionary(x => x.Name, x => (object)x.Name);
  }

对你来说重要的部分是.OrderBy(x =&gt; x.IsSubclassOf(typeof(Base))),它将订购属性。

【讨论】:

  • 我使用了上面的回复,但我得到了一本包含大量数据的字典,不仅包括属性@Shoejep 你能帮忙吗?我的代码是: List props = Assembly .GetAssembly(typeof(T)) .GetTypes() .OrderBy(x => x.IsSubclassOf(typeof(BaseAuctionDataSum))) .SelectMany(x => x.GetProperties() ) .GroupBy(x => x.Name) .Select(x=>x.First()) .ToList();为什么我得到的记录比我预期的多?
  • 我创建了一个 .Net 小提琴,说明您应该如何使用我的答案:dotnetfiddle.net/vqzR3k,因为在您的评论中,我不知道“T”或“BaseAuctionDataSum”是什么类型。
  • 我又试了一次,但遇到了同样的问题,正如你在我的小提琴附件中看到的 dotnetfiddle.net/zuRNaz ,如果程序集中还有更多的类,我也会得到它们的属性,但我只想要我的基类和派生类的属性
  • 糟糕,我的错,我添加了另一个小提琴,它只挑选基本类型和派生类型:dotnetfiddle.net/jVTBYP
猜你喜欢
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多