访问System.Action中的对象属性

问题描述 投票:0回答:2

有两个类:

public abstract class BaseObject
{
    public string Status {get; set;}

    public List<string> StatusHistory {get; set;}

    protected abstract void ExecuteInternal();

    public void Execute()
    {
        this.Status = "Started";

        this.ExecuteInternal();

        this.Status = "Finished";
    }

    // on status changed event: adding current status to StatusHistory list
}

public class SomeObject : BaseObject
{
    public System.Action Action {get; set;}

    public SomeObject() : this(null)
    {
    }

    public SomeObject(System.Action action)
    {
        this.Action = action;
    }

    protected override void ExecuteInternal()
    {
        this.Action();
    }
}

使用此对象,我想要及时设置Status属性Action将被执行:

 const string customStatus = "Custom status";

 var someObject= new SomeObject(() => Status = customStatus);

 someObject.Execute();

验证customStatus确实已设置:

 if (!HistoryStatus.Contains(customStatus))
 {
     // throw an exception
 }

这里发生错误:当前上下文中不存在名称“Status”。

我如何在Action中设置属性?

c# delegates
2个回答
2
投票

说实话,这是过于复杂的事情,我强烈建议使用对象初始化语法:

var someObject = new SomeObject() { Status = customStatus};

不过,您可以使用System.Action<SomeObject>解决当前问题,System.Action指定预期的输入类型而不是class SomeObject { public System.Action<SomeObject> Action {get; set;} public string Status {get; set;} public SomeObject() : this(null) { } public SomeObject(System.Action<SomeObject> action) { this.Action = action; } public void Execute() { this.Action(this); } } 然后修改代码中的相应位置:

const string customStatus = "Custom status";
var someObject= new SomeObject((s) => s.Status = customStatus);

然后调用如下:

        const string customStatus = "Custom status";

        var someObject = new SomeObject();

        someObject.Action = () => someObject.Status = customStatus;

0
投票

我需要这样的东西:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.