[英]Getting the count property value of a list property inside a class with reflection
I have the following classes:我有以下课程:
class Topping
{
public string Name {get; set;}
}
class Pizza
{
public List<Topping> Toppings {get ; set;}
public Pizza()
{
this.Toppings = new List<Topping>();
}
}
Suppose i have a list of pizzas inside Main假设我在 Main 中有一个比萨饼列表
Is there a way to get the value of the Count property of the Toppings list inside the Pizza class, using reflection ?有没有办法使用反射获取 Pizza 类中 Toppings 列表的 Count 属性的值?
I tried something like this:我试过这样的事情:
foreach(var pizza in Pizza)
{
int countValue = pizza.GetType().GetProperty("Toppings").GetType().GetProperty("Count").GetValue(pizza);
}
When calling GetValue
, you should provide instances of pizza
and list
, eg (if you insist on reflection):在调用
GetValue
,您应该提供pizza
和list
实例,例如(如果您坚持反射):
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
}
Straightforward coding will be简单的编码将是
foreach (var pizza in Pizza) {
// If pizza or Toppings is null, let's have -1 for countValue
int countValue = pizza
?.Toppings
?.Count ?? -1;
}
I agree with Dmitry Bychenko, but I think in real case you don't need to use Reflection.我同意 Dmitry Bychenko,但我认为在实际情况下您不需要使用反射。
Event if you don't know the type of the list ( Topping
in your case), you can always cast a list to ICollection.如果您不知道列表的类型(在您的情况下为
Topping
),则始终可以将列表转换为 ICollection。
The definition of list is this:列表的定义是这样的:
public class List<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IList
And ICollection
has a Count property.并且
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; }
So this code should works:所以这段代码应该有效:
var count = (pizza.Topping as ICollection).Count;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.