访问System.Action中的对象属性

时间:2018-12-05 09:18:36

标签: c# delegates

有两个类:

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属性,以执行操作:

 const string customStatus = "Custom status";

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

 someObject.Execute();

验证是否确实设置了customStatus:

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

出现错误:当前上下文中不存在名称“状态”。

如何在操作中设置属性?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

我需要这样的东西:

        const string customStatus = "Custom status";

        var someObject = new SomeObject();

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