我如何从lambda表达式返回模型属性(如MVC's "Html.TextBoxFor(xxx)&qu

本文关键字:quot TextBoxFor qu xxx Html MVC lambda 表达式 返回 属性 模型 | 更新日期: 2023-09-27 17:50:26

在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; }

我想定义一个Dictionary对象,以Enum Actions作为键,以属性作为值:

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 }
}

我需要传递属性,而不是属性值到字典中,因为它们可能在运行时发生变化。

想法?

我如何从lambda表达式返回模型属性(如MVC's "Html.TextBoxFor(xxx)&qu

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

Dictionary<Actions, Func<bool>>

然后可以对lambdas求值以获得属性的运行时值:

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

听说过表达式树吗?Charlie Calvert关于表达式树的介绍

假设你想定义一个方法,它接受一个string属性的引用;一种方法是使用一个方法:

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));
}

更多参考链接:

表达式树和lambda分解

关于表达式树的CodeProject教程

在API中使用表达式树

The Amazing Bart de Smet on Expression Trees