簡體   English   中英

如何在C#中將屬性作為參數傳遞

[英]How to pass property as parameter in C#

假設我有一堂課

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

我有一個方法parseData(List<Item> items, <reference to property>)應該迭代items並從每個項目中僅獲取必需的屬性。 在C#中最有效的方法是什么。 我應該為此使用Expression嗎(但我不知道該怎么做)?

要獲得屬性,您可能可以使用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());
    ...
}

您可以通過傳遞lambda表達式來調用此方法:

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

如果你願意的話

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