[英]how to get the “class type” of a property in a class through reflection?
here is a piece of code 这是一段代码
public class Order
{
//Primary Key
public long OrderId { get; set; }
//Many to One Relationship
[ParentObject("PersonId")]
public Person Buyer { get; set; }
//One to Many Relationship
[ChildObject("OrderId")]
public List<OrderDetail> OrderDetails { get; set; }
public decimal TotalAmount
{
get
{
if (OrderDetails == null)
return 0;
return OrderDetails.Sum(o => o.LineItemCost);
}
}
public string Notes { get; set; }
}
I am trying to examine the Order object. 我正在尝试检查Order对象。 Now what I want to do is that: get all the properties and try to find out the class type for instance
现在我要做的是:获取所有属性并尝试找出实例的类类型
public List<OrderDetail> OrderDetails { get; set; }
I want to get the type "OrderDetail" that is another class. 我想获取另一个类的类型“ OrderDetail”。 When I try to get it using PropertyInfo.PropertyType I get "List1" (the Generic type), PropertyInfo.GetType() gives some System.Reflection.RuntimeType, PropertyInfo.DeclaringType gives "Order" (the class that contains the property).
当我尝试使用PropertyInfo.PropertyType来获取它时,我得到“ List1”(通用类型),PropertyInfo.GetType()给出了一些System.Reflection.RuntimeType,PropertyInfo.DeclaringType给出了“ Order”(包含该属性的类)。 I would be obliged if anyone can propose a solution.
如果有人可以提出解决方案,我将有义务。 Thanks in advance.
提前致谢。
您可以使用GetGenericArguments()方法并执行以下操作:
typeof(Order).GetProperty("OrderDetails").PropertyType.GetGenericArguments()[0]
The type returned by PropertyInfo.PropertyType would be typeof(List<OrderDetail>)
PropertyInfo.PropertyType返回的类型为
typeof(List<OrderDetail>)
using this you can get the type arguments using Type.GetGenericArguments()
使用此,您可以使用
Type.GetGenericArguments()
获得类型参数。
Type propertyType = property.PropertyType;
if(propertyType.IsGeneric && propertyType.GetGenericTypeDefinition() == typeof(List<>))
{
Type argType = propertyType.GetGenericArguments()[0];
// argType will give you your OrderDetail
}
Are you looking for how to know about generic arguments? 您是否正在寻找有关通用参数的信息?
Let's say you've an instance of Order in some variable like "someOrder": 假设您在某个变量(例如“ someOrder”)中有一个Order实例:
someOrder.OrderDetails.GetType().GetGenericArguments();
Since List has a single generic parameter, Type.GetGenericArguments method will return an array of an item: Order type. 由于List具有单个通用参数,因此Type.GetGenericArguments方法将返回以下项的数组:订单类型。
It's solving your problem, isn't it? 它正在解决您的问题,不是吗?
It seems you didn't know that OrderDetails type is List`1 (a generic list with a single generic parameter). 似乎您不知道OrderDetails类型是List`1(具有单个通用参数的通用列表)。 PropertyInfo.PropertyType exposes that because the type of such property is a generic list.
PropertyInfo.PropertyType公开了这一点,因为此类属性的类型是通用列表。 You want to know the generic type of that generic list.
您想知道该通用列表的通用类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.