我的代码:
namespace Reflection
{
class Program
{
static void Main(string[] args)
{
Type t = typeof(Product);
PropertyInfo[] proInfo = t.GetProperties();
foreach (var item in proInfo)
{
Console.WriteLine(item.Name);
}
}
}
public class Product
{
public int ProId { get; set; }
public string ProName { get; set; }
public string Description { get; set; }
public decimal UnitPrice { get; set; }
}
我得到所有属性名称作为输出。但我不想在输出中显示ProId和Decription。我怎么能这样做????
答案 0 :(得分:0)
您需要向要么/不希望在列表中显示的字段添加属性,然后在执行GetProperties()
后通过查找所述属性将其过滤掉。
答案 1 :(得分:0)
一个简单的解决方案,如果你只有2个你不想展示的属性,那就是专门过滤它们。您可以使用LINQ的 Where :
Type t = typeof(Product);
PropertyInfo[] proInfo = t.GetProperties().Where( p => p.Name != "ProdId" && p.Name != "Description").ToArray() ;
foreach (var item in proInfo)
{
Console.WriteLine(item.Name);
}
甚至是这样的事情:
string[] dontShow = { "ProId", "Descrpition" };
Type t = typeof(MyObject);
PropertyInfo[] proInfo = t.GetProperties()
.Where(p => !dontShow.Contains(p.Name)).ToArray();