lambda Expression作为属性

Pro*_*aos 9 c# lambda expression

我有一个工作设置,不是强类型,依赖于反射.

说,我有一节课

class Person{

    public string FirstName {get ; set;}
    public string LastName {get; set;}
    public int Age {get; set;}
    ...  
    // some more public properties
}
Run Code Online (Sandbox Code Playgroud)

class CellInfo {
     public string Title {get; set;}
     public string FormatString {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我有这样的字典

Dictionary<string, CellInfo> fields = new Dictionary<string, CellInfo>();
fields.Add("FirstName", new CellInfo {Title = "First Name", FormatString = "Foo"});
fields.Add("LastName", new CellInfo {Title = "Last Name", FormatString = "Bar"});
Run Code Online (Sandbox Code Playgroud)

这是一个简单的字典,其中包含属性Names和一些有关它们的信息.我将字典传递给另一个处理Person实例的模块

Dictionary<string, CellInfo> fields = SomeMethodToGetDictionary();
foreach(Person p in someCollection)
{
    foreach(var field in fields)
    { 
       object cellValue = type(Person).GetProperty(field.Key).GetValue(p, null);
       // use cellValue and info on field from field.Value somewhere.
       ...
    }
 }
Run Code Online (Sandbox Code Playgroud)

这种传递字符串的字段名称和使用反射的方法有效,但我想知道是否有一种强类型的方法.

我想到的是拥有一个存储linq表达式的属性,就像这样

fields.Add("FirstName", new CellInfo 
                   {
                      Title = "First Name", 
                      FormatString = "Foo",
                      EvalExpression = p => p.FirstName
                   });
Run Code Online (Sandbox Code Playgroud)

在使用过程中,以某种方式使用EvalExpressionon person对象并获取属性值.我不知道从哪里开始或者有什么语法可以像这样具有可评估的属性.我是新手,我甚至不知道要搜索的正确关键字的代理和表达式树.希望我的描述清楚; 如果没有,请告诉我,我会在必要时详细说明.任何援助都会非常感激.

Jan*_*Jan 2

如果这就是您所说的强类型的意思,您可以尝试这样的方法,不必将属性名称编码为字符串:

class CellInfo<T>
{
    public string Title { get; set; }
    public string FormatString { get; set; }
    public Func<T, object> Selector { get; set; }
}

Dictionary<string, CellInfo<Person>> dict = new Dictionary<string, CellInfo<Person>>();

dict.Add("LastName", new CellInfo<Person> { Selector = p => p.LastName });
dict.Add("Age", new CellInfo<Person> { Selector = p => p.Age });

foreach (Person p in someCollection)
{
    foreach (var cellInfo in dict)
    {
        object value = cellInfo.Value.Selector(p);
    }
}
Run Code Online (Sandbox Code Playgroud)