【发布时间】:2020-03-29 03:34:19
【问题描述】:
我正在尝试使用反射来获取声明的类型。它适用于不可为空的类型,但适用于可空类型。
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>
【问题讨论】:
-
“我期望得到 Nullable
” 这不是类型的名称。系统返回给您的名称是。如果您想要在 C# 代码中看到的名称,则由您编写代码以将构造类型的名称转换回 C# 样式的名称。 -
@PeterDuniho 这个问题专门针对可空类型。由于它的语法,例如
decimal?,对于某些人来说他们处理的是泛型类可能并不明显。出于这个原因,我认为这个问题对社区有价值。请考虑重新开放。 -
@JeremyTCD:“这个问题专门针对可空类型”——不,不是。它是关于泛型类型,以及构造泛型类型的 .NET 名称与 C# 程序员习惯看到的名称之间的区别。它与标记的副本完全相同。更糟糕的是,您给出的答案甚至没有完成问题作者所要求的,而标记副本中的建议却做到了。
标签: c# nullable system.reflection propertyinfo