繁体   English   中英

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

[英]How can I return model property from lambda expression (like MVC's “Html.TextBoxFor(xxx)”)?

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

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

有想法吗?

-布伦丹

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

Dictionary<Actions, Func<bool>>

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

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

听说过表达树吗? 查理·卡尔弗特(Charlie Calvert)关于表达树的介绍

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

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

通过表达式树,您可以执行FAR FAR而不是此操作。 我衷心建议在那里做一些研究。 :)

编辑:另一个例子

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中使用表达式树

表情树上的惊人Bart de Smet

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM