簡體   English   中英

如何在C#中使用反射獲取列表類型元素

[英]How to get list type elements using reflection in c#

我有一個課:Transaction.cs

public class Transaction
{
    public int Transaction_id  { get; set; }
    public string Description { get; set; }
    public string Item { get; set; }
}

我也想使用反射來獲取事務集合中的值,即:

var db = new List<Transaction>();
var temp = new Transaction { Transaction_id = 123, Item = "AKP", Description = "Startup" };
var info = temp.GetType().GetProperties();
db.Add(new Transaction { Transaction_id = 45, Item = "RW", Description = "Starting" });
var type = typeof(Transaction);
var prop = type.GetProperty("Item");
var value = prop.GetValue(temp);

將此代碼添加到屬性循環中:

foreach (var testing in db.GetType().GetProperties())
{
    var sample = testing.GetValue(db);
    Console.WriteLine(sample);
}

我在命令行中顯示的值為4。

這將使我在屏幕上看到AKP的價值。 現在,當我有交易清單時,它如何運作?

謝謝

例如,如果我想將所有屬性設置為string.Empty,則可以在類中執行類似的操作,您可以在foreach循環中應用相同的邏輯來獲取屬性類型等。

public static void ConvertNullToStringEmpty<T>(this T clsObject) where T : class
{
    PropertyInfo[] properties = clsObject.GetType().GetProperties();//typeof(T).GetProperties();
    foreach (var info in properties)
    {
        // if a string and null, set to String.Empty
        if (info.PropertyType == typeof(string) && info.GetValue(clsObject, null) == null)
        {
            info.SetValue(clsObject, String.Empty, null);
        }
    }
}

考慮到您有以下列表:

var transactionList = new List<Transaction>
{
   new Transaction { Transaction_id = 123, Item = "AKP", Description = "Startup" },
   new Transaction { Transaction_id = 45, Item = "RW", Description = "Starting" }
};

您可以通過在迭代列表時讀取單個項目的屬性來導航集合中每個項目的屬性名稱:

foreach (var item in transactionList)
{
     foreach (var property in item.GetType().GetProperties())
     {
         Console.WriteLine("{0}={1}", property.Name, property.GetValue(item, null));
     }                
}

Console.ReadLine();

泛型列表是類型安全的,因此您無需使用反射。

要遍歷列表,請使用foreach

var db = new List<Transaction>
{
    new Transaction { Transaction_id = 123, Item = "AKP", Description = "Startup" }, 
    new Transaction { Transaction_id = 45, Item = "RW", Description = "Starting" }
}
foreach (var transaction in db)
{
    Console.WriteLine(transaction.Item);
}

輸出:

AKP
RW

如果您確實需要使用Reflection,並且這種情況在您的代碼庫中很常見,那么我將花時間編寫這樣的擴展方法:

static T GetPropertyByName<T>(this object input, string name) 
{
    return (T)input
        .GetType()
        .GetProperty(name, BindingFlags.Instance)
        .GetValue(input);
}

並像這樣使用它:

foreach (var transaction in db)
{
    Console.WriteLine(transaction.GetPropertyByName<string>("Item"));
}

或者,如果您不提前知道屬性的名稱,請執行以下操作:

foreach (var row in db)
{
    foreach (var p in row.GetType().GetProperties(BindingFlags.Instance))
    {
        Console.WriteLine(p.GetValue(row));
    }
}

暫無
暫無

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

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