简体   繁体   English

如何在C#中将属性作为参数传递

[英]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. 我有一个方法parseData(List<Item> items, <reference to property>)应该迭代items并从每个项目中仅获取必需的属性。 What is the most effective way to do it in C#. 在C#中最有效的方法是什么。 Should I use Expression for this (but I cannot figure out how to do it)? 我应该为此使用Expression吗(但我不知道该怎么做)?

To get a property, you could probably use a Func<Item, T> : 要获得属性,您可能可以使用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: 您可以通过传递lambda表达式来调用此方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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