C#制作了Lambda的字典

Adr*_*zar 5 c# lambda expression-trees

我在定义快速访问Lambda表达式的字典时遇到了麻烦.

我们假设我们有一个这样的知名类:

class Example
{
    public string Thing1;
    public DateTime Thing2;
    public int Thing3;
}
Run Code Online (Sandbox Code Playgroud)

想要做的是这样的事情:

var getters = new Dictionary<string, IDontKnowWhatGoesHere>();
getters.Add("Thing1", x => x.Thing1);
getters.Add("Thing3", x => x.Thing3);
Run Code Online (Sandbox Code Playgroud)

这可能吗?

编辑:

这是我对这个对象的用例:

List<Example> array = new List<Example>();

// We actually get this variable set by the user
string sortField = "Thing2";

array.Sort(getters[sortField]);
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助.

Roa*_*ich 8

你有几个选择.如果在你的例子中,你想要得到的东西都是相同的类型(即String),你可以这样做

var getters = new Dictionary<string, Func<Example, String>>();
Run Code Online (Sandbox Code Playgroud)

但是,如果它们是不同的类型,则需要使用最低的公共子类,在大多数情况下,它将是Object:

var getters = new Dictionary<string, Func<Example, object>>();
Run Code Online (Sandbox Code Playgroud)

请注意,您需要将返回值强制转换为预期类型.