简体   繁体   English

如何使用C#明确方法调用顺序?

[英]How can I make method invocation order explicit with C#?

How can I make method invocation order explicit with C#? 如何使用C#明确方法调用顺序?

I want to make it explicit in code that one method should be called before the other, somewhat similar to the way callbacks work in JavaScript. 我想在代码中明确指出一种方法应该在另一种方法之前调用,这有点类似于JavaScript中的回调方法。 I'm thinking that something like an array or List of Action might do the trick, but am not sure if this the best way, given what I am trying to achieve - it winds up being a better experience for the user if things happen in a certain order, but I want to make this explicit through code, instead of adding a comment. 我在想像数组或动作列表之类的方法可能会解决问题,但是鉴于我要实现的目标,我不确定这是否是最好的方法-如果事情发生了,它将为用户带来更好的体验确定顺序,但我想通过代码使其明确,而不是添加注释。

Here's what I have so far: 这是我到目前为止的内容:

Action<dynamic>[] deleteOperations = new Action<dynamic>[2];
deleteOperations[0] = (resource => this.RemoveImageFromDatabase(resource));
deleteOperations[1] = (filename => _blobStorage.DeleteBlob(filename));

That can be a difficult question, especially without more information. 这可能是一个困难的问题,尤其是在没有更多信息的情况下。 Why not provide a method that performs the desired actions in the order that you require? 为什么不提供一种按所需顺序执行所需操作的方法?

void Delete(Resource resource, String filename) {
    try {
        this.RemoveImageFromDatabase(resource);
        }
    catch {
        }
    try {
        _blobStorage.DeleteBlob(filename);
        }
    catch {
        }
    }

This ensures that order is as required and gives you greater control over the operation (allowing you to log exceptions for example). 这样可以确保按要求排列顺序,并可以更好地控制操作(例如,允许您记录异常)。

Have you looked into temporal coupling? 您是否研究过时间耦合? Basically, you make the second function dependent on the first. 基本上,您使第二个函数依赖于第一个。

I don't know if this will help in your situation, but you end up with something like this: 我不知道这对您的情况是否有帮助,但是您最终会得到如下结果:

var first = FirstMethod(p1, p2);
var second = SecondMethod(first, p3);

With the second call dependent on the first, you can't call them out of order. 由于第二个呼叫依赖于第一个,因此您不能无序呼叫它们。

There are some links and ideas in this thread: 此线程中有一些链接和想法:

How to deal with temporal coupling? 如何处理时间耦合?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM