简体   繁体   English

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

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

I have a class : Transaction.cs 我有一个课:Transaction.cs

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

I want too use reflection to get the values that are in the collection of transactions ie : 我也想使用反射来获取事务集合中的值,即:

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);

added this code for loop on properties: 将此代码添加到属性循环中:

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

i get a value of 4 displayed in command line. 我在命令行中显示的值为4。

which would give me the value of AKP on screen. 这将使我在屏幕上看到AKP的价值。 Now how does it work when i have a list of transactions? 现在,当我有交易清单时,它如何运作?

Thanks 谢谢

For example if I want to set all of the properties to string.Empty in my class I would do something like this, you could apply the same logic in the foreach loop to get your property types etc.. 例如,如果我想将所有属性设置为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);
        }
    }
}

Considering you got this list: 考虑到您有以下列表:

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

You can navigate property names of the each item in the collection by reading a single item's properties while iterating the list: 您可以通过在迭代列表时读取单个项目的属性来导航集合中每个项目的属性名称:

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

Console.ReadLine();

Generic lists are type-safe so you don't need to use reflection. 泛型列表是类型安全的,因此您无需使用反射。

To iterate over the list, use foreach . 要遍历列表,请使用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);
}

Output: 输出:

AKP
RW

If you truly need to use Reflection, and this sort of thing is common in your code base, I'd take the time to write an extension method like this one: 如果您确实需要使用Reflection,并且这种情况在您的代码库中很常见,那么我将花时间编写这样的扩展方法:

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

And use it like this: 并像这样使用它:

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

Or if you don't know the names of the properties ahead of time: 或者,如果您不提前知道属性的名称,请执行以下操作:

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