如何从lambda表达式返回模型属性(如MVC的“Html.TextBoxFor(xxx)”)?

时间:2013-01-02 00:09:55

标签: c# linq properties lambda

在MVC中你可以说:

Html.TextBoxFor(m => m.FirstName)

这意味着您将模型属性作为参数(而不是值)传递,因此MVC可以获取元数据等等。

我正在尝试在C#WinForms项目中做类似的事情,但无法弄清楚如何。基本上我在用户控件中有一组bool属性,我想在字典中枚举它们以便于访问:

public bool ShowView { get; set; }
public bool ShowEdit { get; set; }
public bool ShowAdd { get; set; }
public bool ShowDelete { get; set; }
public bool ShowCancel { get; set; }
public bool ShowArchive { get; set; }
public bool ShowPrint { get; set; }

我想以某种方式定义一个以Enum Actions为键的Dictionary对象,并将该属性定义为值:

public Dictionary<Actions, ***Lambda magic***> ShowActionProperties = new Dictionary<Actions,***Lambda magic***> () {
    { Actions.View, () => this.ShowView }
    { Actions.Edit, () => this.ShowEdit }
    { Actions.Add, () => this.ShowAdd}
    { Actions.Delete, () => this.ShowDelete }
    { Actions.Archive, () => this.ShowArchive }
    { Actions.Cancel, () => this.ShowCancel }
    { Actions.Print, () => this.ShowPrint }
}

我需要将属性而不是属性值传递到字典中,因为它们可能会在运行时更改。

想法?

-Brendan

2 个答案:

答案 0 :(得分:3)

您的所有示例都没有输入参数并返回bool,因此您只需使用:

Dictionary<Actions, Func<bool>>

然后,您可以评估lambdas以获取属性的运行时值:

Func<bool> fn = ShowActionProperties[ Actions.View ];
bool show = fn();

答案 1 :(得分:2)

有没有听说过表达树? Charlie Calvert's Intro on Expression Trees

假设您要定义一个引用字符串属性的方法;你可以做到这一点的一种方法是有一个方法:

public string TakeAProperty(Expression<Func<string>> stringReturningExpression)
{
    Func<string> func = stringReturningExpression.Compile();
    return func();
}

然后您可以通过以下方式致电:

void Main()
{
    var foo = new Foo() { StringProperty = "Hello!" };
    Console.WriteLine(TakeAProperty(() => foo.StringProperty));
}

public class Foo
{
    public string StringProperty {get; set;}
}

表达式树让你做远远超过这个,但是;我衷心建议在那里做一些研究。 :)

编辑:另一个例子

public Func<Foo,string> FetchAProperty(Expression<Func<Foo,string>> expression)
{
    // of course, this is the simplest use case possible
    return expression.Compile();
}

void Main()
{
    var foo = new Foo() { StringProperty = "Hello!" };
    Func<Foo,string> fetcher = FetchAProperty(f => f.StringProperty);
    Console.WriteLine(fetcher(foo));
}

更多参考链接:

Expression trees and lambda decomposition

A CodeProject tutorial on Expression Trees

Using Expression Trees in your API

The Amazing Bart de Smet on Expression Trees