【问题标题】:Class with list elements of child class, removing on action of child class?具有子类列表元素的类,删除子类的动作?
【发布时间】:2019-12-13 09:10:21
【问题描述】:

我有一个父类,称之为 Worker,它只有一个子类的元素列表,我们称之为子类。

    public class Worker
    {
        private List<Child> subscriptions = new List<Child>();

        public void Subscribe(string pID)
        {
            Child temp = new Child();
            subscriptions.Add(temp);
        }
    }

我正在做的是每个被创建和添加的 Child 运行一个单独的线程,其中包含一些计算。 现在我得到的情况是,如果子进程失败,无论什么原因,我的父类都无法通知,因此无法从列表中删除“失败的子进程”。 因此,我的问题是:

如何将失败的子类中的“错误”列表元素通知我的父类?

【问题讨论】:

  • 您是否尝试将Action 传递给它从失败代码中调用的子对象?
  • 这听起来完全像我应该尝试的东西,我该如何实现这样的Action
  • 事件或在 Worker 类中创建公共方法 RemoveChild(Child child) 将在发生某些事情时从计算方法开始并删除子项。

标签: c# list class


【解决方案1】:

Worker 想知道Child 何时需要它的注意

这看起来像一个Observer 模式,其中Worker 可以GetFaulty(Child faulty)Child 想要Notify

public class Child
{
    // some code

    public Worker Parent { get; set; }

    // This is called when the process fails
    public void Notify()
    {
        Parent.GetFaulty(this);
    }

    // more code
}

public class Worker
{
    private List<Child> subscriptions = new List<Child>();

    public void Subscribe(string pID)
    {
        Child temp = new Child { Parent = this };
        subscriptions.Add(temp);
    }

    public void GetFaulty(Child faulty)
    {
        subscriptions.Remove(faulty);
    }
}

【讨论】:

  • 谢谢,这正是我几秒钟前解决的方法。很好的解释,谢谢。不是现在这被正式称为设计模式!
  • 我建议你this reading
【解决方案2】:

我知道了怎么做,我只是在创建时将 Worker 作为父属性传递给 Childs,这样我可以在孩子的失败代码中调用 parent.DestroyAction。

我想这不是最佳做法,但它对我有用。

感谢富有洞察力的 cmets!

【讨论】:

    【解决方案3】:

    根据您现有的结构,您可以选择参加这样的活动:

    public class Child
    {
        public event Action<Child> OnFault;
    
        public async Task DoWork()
        {
            try {
                // you do what you gotta do
            }
            catch {
                if(OnFault !=null) OnFault(this);
            }
        }
    }
    
    public class Worker
    {
        private List<Child> subscriptions = new List<Child>();
    
        public void Subscribe(string pID)
        {
            Child temp = new Child();       
            temp.OnFault += (x) => subscriptions.Remove(x); // set an event handler to remove that particular instance from the list
            subscriptions.Add(temp);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2019-11-25
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 2018-08-30
      相关资源
      最近更新 更多