[英]Getting property values of list of child objects
假設我有一個帶有某些屬性的Car
類。 其中一個屬性是另一個類的IEnumerable
,它具有自己的屬性Passenger
。
public class Car
{
public string Engine { get; set; }
public int Wheels { get; set; }
public IEnumerable<Passenger> Passengers { get; set }
}
我能夠獲取Engine和Wheels屬性的值(以及所有其他此類屬性)。 但是,我不知道如何獲取所有Passenger
對象的屬性。 這是我要獲取Car
對象的屬性值的操作:
Type type = car.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
object carValue = property.GetValue(car, null);
Console.WriteLine(carValue.ToString());
}
顯然,這並沒有給我Passenger
屬性,而是輸出了以下內容:
System.Collections.GenericList'1[Passenger]
如何獲取car.Passengers
每位Passenger
所有財產價值? Passenger
列表?
您可以將Type.IsGenericType
和Type.GetGenericTypeDefinition()
混合使用。
private void DisplayObject(object obj)
{
var type = obj.GetType();
foreach(var propertyInfo in type.GetProperties())
{
object value = propertyInfo.GetValue(obj, null);
if(propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
foreach(object o in (IEnumerable)value)
{
DisplayObject(o);
}
}
else
{
Console.WriteLine(value);
}
}
}
您將必須首先檢查Car
的屬性是否為IEnumerable
,如果是,則必須在其上再次使用反射。 最好使用以下遞歸來完成:
您的汽車對象:
public class Car
{
public string Engine { get; set; }
public int Wheels { get; set; }
public IEnumerable<Passenger> Passengers { get; set; }
}
樣例應用:
internal class Program
{
private static void Main(string[] args)
{
var car = new Car
{
Engine = "1234",
Wheels = 4,
Passengers = new List<Passenger>
{
new Passenger
{
Id = 1,
Name = "Bhushan"
}
}
};
ReflectObject(car);
Console.ReadKey();
}
使用的功能:
private static void ReflectObject(object objectToReflect)
{
foreach (var propertyInfo in objectToReflect.GetType().GetProperties())
{
object propertyValue = propertyInfo.GetValue(objectToReflect, null);
if (IsEnumerable(propertyInfo))
{
foreach (object obj in (IEnumerable)propertyValue)
{
ReflectObject(obj);
}
}
else
{
Console.WriteLine(propertyValue);
}
}
}
private static bool IsEnumerable(PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}
}
輸出:
1234
4
1
布尚
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.