【问题标题】:Getting the count property value of a list property inside a class with reflection使用反射获取类中列表属性的计数属性值
【发布时间】:2020-10-16 10:17:48
【问题描述】:

我有以下课程:

class Topping
{
   public string Name {get; set;}
}

class Pizza
{
    public List<Topping> Toppings {get ; set;}

    public Pizza()
    {
       this.Toppings = new List<Topping>();
    }
}

假设我在 Main 中有一个比萨饼列表

有没有办法使用反射来获取 Pizza 类中 Toppings 列表的 Count 属性的值?

我尝试过这样的事情:

foreach(var pizza in Pizza)
{
   int countValue = pizza.GetType().GetProperty("Toppings").GetType().GetProperty("Count").GetValue(pizza);
}

【问题讨论】:

  • 首先你必须得到List&lt;Topping&gt;实例然后你必须得到这个实例的Count属性(不是披萨)
  • 你有一个很好的答案stackoverflow.com/a/3546220/1543596
  • @Ygalbel 不,这是关于 Enumerable Count ... 这是一种方法而不是属性

标签: c# list reflection


【解决方案1】:

调用GetValue 时,应提供pizzalist实例,例如(如果你坚持反思):

foreach (var pizza in Pizza) {
  var list = pizza
    .GetType()
    .GetProperty("Toppings")
    .GetValue(pizza); // we want list of Toppings for the pizza instance
 
  int countValue = (int) (list 
    .GetType()
    .GetProperty("Count")
    .GetValue(list)); // we want Count for list (i.e. pizza.Toppings) instance    
}

简单的编码将是

foreach (var pizza in Pizza) {
  // If pizza or Toppings is null, let's have -1 for countValue
  int countValue = pizza
    ?.Toppings
    ?.Count ?? -1; 
}

【讨论】:

    【解决方案2】:

    我同意 Dmitry Bychenko 的观点,但我认为在实际情况下您不需要使用反射。

    如果您不知道列表的类型(在您的情况下为Topping),您可以随时将列表强制转换为 ICollection。

    列表的定义是这样的:

    public class List<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IList
    

    ICollection 有一个 Count 属性。

     /// <summary>Defines size, enumerators, and synchronization methods for all nongeneric collections.</summary>
      public interface ICollection : IEnumerable
      {
        /// <summary>Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"></see>.</summary>
        /// <returns>The number of elements contained in the <see cref="T:System.Collections.ICollection"></see>.</returns>
        int Count { get; }
    

    所以这段代码应该可以工作:

    var count = (pizza.Topping as ICollection).Count;
    

    【讨论】:

    • 谢谢,这个也不错,但是由于我们学校的问题坚持使用反射,我必须这样完成:D
    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2018-06-05
    • 2011-10-02
    • 2013-01-16
    相关资源
    最近更新 更多