如何使用反射获取声明的类型

问题描述 投票:0回答:1

我正在尝试使用反射来获取声明的类型。对于非可空类型,它工作正常,但对于可空类型,则失败。

class Product
{
    public decimal Price { get; set; }
    public decimal? OfferPrice { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        Type t = typeof(Product);
        var properties = t.GetProperties();
        PropertyInfo price_pInfo = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name == "Price").FirstOrDefault();
        Console.WriteLine("Member 'Price' was defined as " + price_pInfo.PropertyType);


        PropertyInfo offerprice_pinfo = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name == "OfferPrice").FirstOrDefault();
        Console.WriteLine("Member 'OfferPrice' was defined as " + offerprice_pinfo.PropertyType);

    }

输出:

Member 'Price' was defined as System.Decimal
Member 'OfferPrice' was defined as System.Nullable`1[System.Decimal] //I am expecting to get Nullable<System.Decimal>
c# nullable system.reflection propertyinfo
1个回答
0
投票

添加方法:

public static Type GetNormalizedType(Type type)
{
    if (type.IsGenericType && 
        type.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        return type.GetGenericArguments()[0];
    }

    return type;
}

然后:

static void Main(string[] args)
{
    Type t = typeof(Product);
    var properties = t.GetProperties();
    PropertyInfo price_pInfo = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name == "Price").FirstOrDefault();
    Console.WriteLine("Member 'Price' was defined as " + GetNormalizedType(price_pInfo.PropertyType));


    PropertyInfo offerprice_pinfo = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name == "OfferPrice").FirstOrDefault();
    Console.WriteLine("Member 'OfferPrice' was defined as " + GetNormalizedType(offerprice_pinfo.PropertyType));
}
© www.soinside.com 2019 - 2024. All rights reserved.