我正在尝试使用反射获取声明的类型。它对于不可为空的类型工作正常,但对于可为空的类型则失败。
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>
decimal?
是Nullable<decimal>
的语法糖,这是一个泛型类型。 运行时将Nullable<decimal>
表示为"System.Nullable'1[十进制]"。来自官方文档:
泛型类型的名称以反引号 (') 结尾,后跟表示泛型类型参数数的数字。此名称重整的目的是允许编译器支持在同一作用域中具有相同名称但具有不同类型参数数量的泛型类型。
没有内置方法来检索泛型类型的代码表示形式,您必须手动编辑类型名称。由于您只关心Nullable<T>
:
public static string GetNullableTypeCodeRepresentation(string typeName)
{
return Regex.Replace(typeName, @".Nullable`1[(.*?)]", ".Nullable<$1>");
}
然后:
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 " + GetNullableTypeCodeRepresentation(offerprice_pinfo.PropertyType.ToString()));
}
指纹:
Member 'Price' was defined as System.Decimal
Member 'OfferPrice' was defined as System.Nullable<System.Decimal>