3

这是一段代码

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

我正在尝试检查 Order 对象。现在我想做的是:获取所有属性并尝试找出类类型,例如

public List<OrderDetail> OrderDetails { get; set; }

我想获得另一个类的“OrderDetail”类型。当我尝试使用 PropertyInfo.PropertyType 获取它时,我得到“List1”(通用类型),PropertyInfo.GetType() 给出了一些 System.Reflection.RuntimeType,PropertyInfo.DeclaringType 给出了“Order”(包含属性的类)。如果有人可以提出解决方案,我将不胜感激。提前致谢。

4

3 回答 3

4

You can use the GetGenericArguments() method and do:

typeof(Order).GetProperty("OrderDetails").PropertyType.GetGenericArguments()[0]
于 2011-04-16T08:29:02.017 回答
2

The type returned by PropertyInfo.PropertyType would be typeof(List<OrderDetail>)

using this you can get the type arguments using Type.GetGenericArguments()

Type propertyType = property.PropertyType;

if(propertyType.IsGeneric && propertyType.GetGenericTypeDefinition() == typeof(List<>))
{
    Type argType = propertyType.GetGenericArguments()[0];
    // argType will give you your OrderDetail
}
于 2011-04-16T08:28:38.400 回答
1

您是否正在寻找如何了解泛型参数?

假设您在某个变量(例如“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.

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). PropertyInfo.PropertyType exposes that because the type of such property is a generic list. You want to know the generic type of that generic list.

于 2011-04-16T08:28:10.310 回答