2013-04-25 93 views
1

我有一個方法獲取對象的屬性的值,並附加一些逗號。我想製作這個generinc,所以我可以將它與其他對象一起使用。如何循環訪問c#中的對象的屬性?

  foreach (var row in rows.ToList()) 
      { 
       sbResult.Append(
        delimiter + row.MediaName + delimiter + separator + 
        delimiter + row.CountryName + delimiter + separator + 
        delimiter + row.ItemOverRideDate + delimiter + separator + 
        delimiter + row.Rating + delimiter + separator + 
        delimiter + row.BatchNo + delimiter + separator + 
        delimiter + row.NoInBatch + delimiter + separator + 
        delimiter + row.BatchDate + delimiter + separator + 
        delimiter + row.DataType + delimiter + separator + 
        delimiter + row.ByLine + delimiter + separator + 
        delimiter + row.IssueNo + delimiter + separator + 
        delimiter + row.Issue + delimiter + separator + 
        delimiter + row.MessageNo + delimiter + separator + 
        delimiter + row.Message + delimiter + separator + 
        delimiter + row.SourceName + delimiter + separator + 
        delimiter + row.SourceType + delimiter + separator); 

       //end of each row 
       sbResult.AppendLine(); 
      } 

我一直在使用var rowData = row.GetType().GetProperties();嘗試,但它只返回屬性本身,我不知道如何獲取屬性的值。

+3

我建議你保存,如果你想在它們之間迭代特性的數據結構(如字典或ArrayList中)。 – Patashu 2013-04-25 12:25:10

回答

2

由於Type.GetProperties返回PropertyInfo的集合,因此請通過致電PropertyInfo.GetValue來追蹤該問題。這裏是你如何能做到這一點(和所有其餘一起)與LINQ:

var line = string.Join(
      row.GetType().GetProperties() 
       .Select(pi => pi.GetValue(row)) 
       .Select(v => delimiter + v.ToString() + delimiter), 
      separator); 

但是,您可能要重新考慮你的方法。如果GetProperties獲取靜態屬性或索引器以及「常規」屬性,則此代碼將中斷;它還要求代碼以完全信任的方式運行(否則不能反射)。最後,它將會是slow,因爲a)反射本質上很慢,b)它會一直反覆重複同樣的事情,而不會緩存它已經發現的任何信息。

除了上述潛在的問題,如果您甚至有遠程機會希望過濾打印出來的內容,最好將此邏輯封裝在row的(virtual?)方法中,像

sbResult.AppendLine(row.SerializeAsLine()); 
0
var values = instance 
    .GetType() 
    .GetProperties(BindingFlags.Instance | BindingFlags.Public) 
    .Select(z => string.Format("{0}: {1}\n", z.Name, z.GetValue(instance, null))); 

string res = string.Concat(values); 

其中instance是您的對象的實例。如果需要StringBuilder(取決於屬性的數量),您可能需要避免使用LINQ並使用循環。

0

您可以使用這樣的事情來遍歷特定類型的所有屬性:

public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj) 
{ 
    return from p in obj.GetType().GetProperties() 
      where p.PropertyType == typeof(T) 
      select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj)); 
} 

然後,你可以指定類型爲string所有你的字符串屬性。

可編譯樣品:

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     private static void Main() 
     { 
      var test = new Test 
      { 
       Str1 = "S1", 
       Str2 = "S2", 
       Str3 = "S3", 
       Str4 = "S4" 
      }; 

      foreach (var property in PropertiesOfType<string>(test)) 
      { 
       Console.WriteLine(property.Key + ": " + property.Value); 
      } 
     } 

     public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj) 
     { 
      return from p in obj.GetType().GetProperties() 
        where p.PropertyType == typeof(T) 
        select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj)); 
     } 
    } 

    public class Test 
    { 
     public string Str1 { get; set; } 
     public string Str2 { get; set; } 
     public string Str3 { get; set; } 
     public string Str4 { get; set; } 
    } 
} 
0

這。

List<PropertyInfo> _propInfo = _row.GetType().GetProperties(); 

    foreach (var item in _propInfo) 
    { 
    object _value = item.GetValue(_row, null); 
    if (_value != null) 
    { 
    // Save the Value 
    } 
    } 
0

GetProperties返回PropertyInfo數組,所以使用GetValue方法和使用的對象,因爲它的投入,得到每個屬性的值。下面是代碼:

public class MyClass 
{ 
    public string MyProperty1 { get; set; } 
    public string MyProperty2 { get; set; } 
    public string MyProperty3 { get; set; } 
} 

然後

MyClass myObj = new MyClass() { MyProperty1 = "first", MyProperty2 = "second", MyProperty3 = "third" }; 

List<string> array = new List<string>(); 

foreach (var item in typeof(MyClass).GetProperties()) 
{ 
    array.Add(item.GetValue(myObj, null).ToString()); 
} 

var result = string.Join(",", array); //use your own delimiter