.NET C# 设置 lambda 选择器定义的字段的值

发布于 2024-08-29 14:10:54 字数 656 浏览 1 评论 0原文

我有一个通用类 HierarchicalBusinessObject。在类的构造函数中,我传递了一个 lambda 表达式,该表达式定义了 TModel 字段的选择器。

protected HierarchicalBusinessObject
    (Expression<Func<TModel,string>> parentSelector)

例如,调用看起来像这样:

public class WorkitemBusinessObject : 
    HierarchicalBusinessObject<Workitem,WorkitemDataContext>
{
    public WorkitemBusinessObject() 
       : base(w => w.SuperWorkitem, w => w.TopLevel == true)
    { }
}

我能够使用选择器在类中进行读取。例如:

sourceList.Select(_parentSelector.Compile()).Where(...

现在我问自己如何使用选择器为字段设置值。 像这样的东西 选择器.Body() .... 字段...

I have a generic class HierarchicalBusinessObject. In the constructor of the class I pass a lambda expression that defines a selector to a field of TModel.

protected HierarchicalBusinessObject
    (Expression<Func<TModel,string>> parentSelector)

A call would look like this, for example:

public class WorkitemBusinessObject : 
    HierarchicalBusinessObject<Workitem,WorkitemDataContext>
{
    public WorkitemBusinessObject() 
       : base(w => w.SuperWorkitem, w => w.TopLevel == true)
    { }
}

I am able to use the selector for read within the class. For example:

sourceList.Select(_parentSelector.Compile()).Where(...

Now I am asking myself how I could use the selector to set a value to the field.
Something like
selector.Body() .... Field...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

っ左 2024-09-05 14:10:54

我不太清楚为什么你传递一个表达式<>。你可以只传递一个 Func作为选择器和 Action为属性设置值:


protected HierarchicalBusinessObject(Action<TModel,string> parentSetter);

public class WorkitemBusinessObject :  
    HierarchicalBusinessObject 
{ 
public WorkitemBusinessObject()  
       : base( (WorkItem w, string s) => {w.Name = s;}) 
    { } 
}

并像这样使用它:


sourceList.ForEach(w => _parentSetter(w, "NewName"));

I'm not quite sure why you pass an Expression<>. You could just pass a Func<TModel,string> as selector and Action<TModel,string> to set a value to a property:


protected HierarchicalBusinessObject(Action<TModel,string> parentSetter);

public class WorkitemBusinessObject :  
    HierarchicalBusinessObject 
{ 
public WorkitemBusinessObject()  
       : base( (WorkItem w, string s) => {w.Name = s;}) 
    { } 
}

And use it like so:


sourceList.ForEach(w => _parentSetter(w, "NewName"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文