简体   繁体   中英

How to pass property as parameter in C#

Suppose I have a class

class Item
{
    public int A {get; set}
    public int B {get; set}
    public int C {get; set}
} 

I have a method parseData(List<Item> items, <reference to property>) which should iterate through items and get only required property from each item. What is the most effective way to do it in C#. Should I use Expression for this (but I cannot figure out how to do it)?

To get a property, you could probably use a Func<Item, T> :

// I don't know what this method returns so I used "void".
public void ParseData<T>(List<Item> items, Func<Item, T> propertySelector) {
    // as an example, here's how to get the property of the first item in the list
    var firstItemsProperty = propertySelector(items.First());
    ...
}

You can call this method by passing a lambda expression:

ParseData(itemList, x => x.Property1) // "Property1" is a property declared in "Item"

Some Reflection if you will

public void ParseData(List<Item> items, String PropertyName)
{
    foreach (Item item in items)
    {
        var prop = typeof(Item).GetProperty(PropertyName).GetValue(item, null);            
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM