簡體   English   中英

迭代列表中的所有屬性

[英]iterate all properties in the list

我有列表(報告)。 報表具有90個屬性。 我不想寫它們每個屬性以獲得屬性值。 有什么可以從清單中獲得屬性值的

例如:

Dim mReports as new List(Of Reports)
mReport = GetReports()

For each mReport as Report In mReports
   'Here I want get all properties values without writing property names
next

您可以使用反射:

static readonly PropertyInfo[] properties = typeof(Reports).GetProperties();

foreach(var property in properties) {
    property.GetValue(someInstance);
}

但是,它會很慢。

通常,擁有90個屬性的班級的設計不佳。
考慮使用詞典或重新考慮您的設計。

PropertyInfo[] props = 
     obj.GetType().GetProperties(BindingFlags.Public |BindingFlags.Static);
foreach (PropertyInfo p in props)
{
  Console.WriteLine(p.Name);
}

我不太會說VB.NET,但是您可以輕松地將類似的內容轉換為VB.NET。

var properties = typeof(Report).GetProperties();
foreach(var mReport in mReports) {
    foreach(var property in properties) {
       object value = property.GetValue(mReport, null);
       Console.WriteLine(value.ToString());
    }
}

這稱為反射 您可以在MSDN上的 .NET中了解其用法。 我使用Type.GetProperties來獲取屬性列表,並使用PropertyInfo.GetValue來讀取值。 您可能需要添加各種BindingFlags或檢查諸如PropertyInfo.CanRead類的PropertyInfo.CanRead以准確獲取所需的屬性。 此外,如果您有任何索引屬性,則必須將第二個參數相應地調整為GetValue

聽起來很適合反射或元編程(取決於所需的性能)。

var props=typeof(Report).GetProperties();
foreach(var row in list)
foreach(var prop in props)
    Console.WriteLine("{0}={1}",
        prop.Name,
        prop.GetValue(row));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM