开发者

how to get the "class type" of a property in a class through reflection?

开发者 https://www.devze.com 2023-02-25 01:10 出处:网络
here is a piece of code public class Order { //Primary Key public long OrderId { get; set; } //Many to One Relationship

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 Relatio开发者_如何学Gonship
    [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. 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. 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). I would be obliged if anyone can propose a solution. Thanks in advance.


You can use the GetGenericArguments() method and do:

typeof(Order).GetProperty("OrderDetails").PropertyType.GetGenericArguments()[0]


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
}


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.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号