0

我有一个类,Container它有很多IReadOnlyList<(string, int)>属性。

它还有一个TotalCount属性,即所有这些列表的总数。

当然,我可以简单地返回 list1.Count + list2.Count ......但我想看看我是否可以使用TypeDescriptorand更紧凑地完成它PropertyDescriptor

问题似乎是listProperties变量不对,但我不知道我做错了什么。

这是我的代码:

   public class Container
    {

        public IReadOnlyList<(string name, int id)> List1 { get; set; } = new List<(string, int)>();
        public IReadOnlyList<(string code, int id)> List2 { get; set; } = new List<(string, int)>();

        // Lots of other Lists of type IReadOnlyList<(string, int)>
        // ....

        public int TotalCount
        {
            get
            {

                var allProperties = TypeDescriptor.GetProperties(this).Cast<PropertyDescriptor>();
                var listProperties = allProperties.Where(p => p.PropertyType is IReadOnlyList<(string, int)>).ToList();
                var total = listProperties.Sum(pd => (int)pd.GetValue(this));

                return total;

            }
        }
    }
4

0 回答 0