2009-11-04 50 views

回答

2

下將選擇所有屬性/值到一個包含名稱/值對你有興趣的屬性匿名類型的IEnumerable的,它使假設性質是公開的,你正在從該對象的方法訪問。如果屬性未公開,則需要使用BindingFlags來指示您需要非公共屬性。如果來自對象之外,則將this替換爲感興趣的對象。

var properties = this.GetType() 
        .GetProperties() 
        .Where(p => p.Name.StartsWith("Value")) 
        .Select(p => new { 
          Name = p.Name, 
          Value = p.GetValue(this, null) 
         });  
7

使用反射。

public static string PrintObjectProperties(this object obj) 
{ 
    try 
    { 
     System.Text.StringBuilder sb = new StringBuilder(); 

     Type t = obj.GetType(); 

     System.Reflection.PropertyInfo[] properties = t.GetProperties(); 

     sb.AppendFormat("Type: '{0}'", t.Name); 

     foreach (var item in properties) 
     { 
      object objValue = item.GetValue(obj, null); 

      sb.AppendFormat("|{0}: '{1}'", item.Name, (objValue == null ? "NULL" : objValue)); 
     } 

     return sb.ToString(); 
    } 
    catch 
    { 
     return obj.ToString(); 
    } 
} 
1

您可以使用Reflection來完成此操作,獲取該類的PropertyInfo對象並檢查它們的名稱。

3

您可以考慮使用集合或自定義索引器。

public object this[int index] 
{ 
    get 
    { 
     ... 
    } 

    set 
    { 
     ... 
    } 
} 

然後你可以說;

var q = new YourClass(); 
q[1] = ... 
q[2] = ... 
... 
q[30] = ... 
+0

爲什麼downvote?他的問題表明「Value1」到「Value30」這是自定義索引者所做的。 – 2009-11-04 17:08:52