2013-03-06 29 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();