gpt4 book ai didi

c# - List 执行顺序

转载 作者:行者123 更新时间:2023-11-30 20:17:20 25 4
gpt4 key购买 nike

我有一个通用接口(interface),上面有一个返回 int 值的方法,例如以下(简化的)代码。对我来说重要的是,这些应该以特定的顺序调用(例如,ClassA 总是需要在 ClassB 之前调用)。我将如何确保此顺序始终正确。依靠列表创建者不是最好的方法吗?

谢谢。

public interface IMyInterface
{
int DoWork();
}

public class MyClassA : IMyInterface
{
private int _myAccumulator = 100;

public int DoWork()
{
_myAccumulator -= 1;

return _myAccumulator;
}
}

public class MyClassB : IMyInterface
{
private int _myAccumulator = 50;

public int DoWork()
{
_myAccumulator -= 1;

return _myAccumulator;
}
}


public class MyWorker
{
private List<IMyInterface> _myAccumulatorClasses = new List<IMyInterface> { new MyClassA(), new MyClassB() }

public void CallClasses()
{
foreach(var accumulator in myAccumulatorClasses)
{
var value = accumulator.DoWork();

if(value > 0)
break; // Don't call next accumulator if we get a value greater than zero back.
}

}
}

最佳答案

您可以添加 Order接口(interface)的属性:

public interface IMyInterface
{
int DoWork();
int Order { get; }
}

然后,在您的实现中:

public class MyClassA : IMyInterface
{
private int _myAccumulator = 100;

public int DoWork()
{
_myAccumulator -= 1;

return _myAccumulator;
}

public int Order {get { return 1;} }
}

最后,OrderBy当你迭代时:

public class MyWorker
{
private List<IMyInterface> _myAccumulatorClasses = new List<IMyInterface> { new MyClassA(), new MyClassB() }

public void CallClasses()
{
foreach(var accumulator in myAccumulatorClasses.OrderBy(x=>x.Order)))
{
var value = accumulator.DoWork();

if(value > 0)
break; // Don't call next accumulator if we get a value greater than zero back.
}

}
}

这是确保秩序的最安全方式。

然而,List<>保证插入顺序。因此,如果您按特定顺序插入,它们将按该顺序出现:

var list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Add("4");

foreach (var element in list)
{
Console.WriteLine(element);
}

输出:

1
2
3
4

enter image description here

关于c# - List<Interface> 执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44882884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com