簡體   English   中英

使用反射獲取類中列表屬性的計數屬性值

[英]Getting the count property value of a list property inside a class with reflection

我有以下課程:

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);
}

在調用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; 
}

我同意 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM