2013-03-06 28 views
0
仅显示一些属性

我的代码:反射特性的信息:如何在运行时

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; } 
    } 

我得到的所有属性的名称作为output.But我不想显示ProId并能解密输出。怎么我能做些那????

回答

0

您需要添加一个属性到您要/不想显示在列表中的字段,然后通过查找上述属性在执行GetProperties()后将其过滤掉。

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();