我在定義快速訪問Lambda表達式的字典時遇到了麻煩。
讓我們假設我們有一個這樣的知名類:
class Example
{
public string Thing1;
public DateTime Thing2;
public int Thing3;
}
想要做的是這樣的事情:
var getters = new Dictionary<string, IDontKnowWhatGoesHere>();
getters.Add("Thing1", x => x.Thing1);
getters.Add("Thing3", x => x.Thing3);
這可能嗎?
編輯:
這是我對這個對象的用例:
List<Example> array = new List<Example>();
// We actually get this variable set by the user
string sortField = "Thing2";
array.Sort(getters[sortField]);
非常感謝您的幫助。
你有幾個選擇。如果在你的例子中,你想要得到的東西都是相同的類型(即String
),你可以這樣做
var getters = new Dictionary<string, Func<Example, String>>();
但是,如果它們是不同的類型,則需要使用最低的公共子類,在大多數情況下它們將是Object
:
var getters = new Dictionary<string, Func<Example, object>>();
請注意,您需要將返回值強制轉換為預期的類型。
var getters = new Dictionary<string, Expression<Func<Example, object>>>();
但是, string Thing1
應該是公開的。