开发者

.NET C# setting the value of a field defined by a lambda selector

开发者 https://www.devze.com 2022-12-26 20:43 出处:网络
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.

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 wi开发者_运维知识库thin 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...


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"));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号