c# - List<Interface> 执行顺序

标签 c# .net

我有一个通用接口(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/

相关文章:

c# - 如何通过rs485串口发送和接收?

c# - MVC Controller 将整个模型发布到远程 api 操作

c# - 我如何将这个谓词定义为一个函数?

.net - 用于 Blob 写入访问的 SAS 不断导致 Azure 存储出现 403 身份验证错误

c# - 对象初始化和 "Named Constructor Idiom"

C# 正则表达式帮助获取多个值

c# - 顺序等待 VS 连续等待

c# - 使用带有返回值的 C# CodeBehind 调用 jQuery 函数

c# - 如何将 HTTP 响应直接流式传输到网络

c# - 如何在不实例化另一个类的情况下引用该方法?