问题描述
你好,这个问题可能很愚蠢.
Hello this question may be silly.
但是仍然有任何方法可以将先决条件实现为另一种方法.我正在使用Visual Studio(可能没有关系).
But still is there any way of implementing prerequisites as a method for another method. I am using Visual studio(may not matter).
示例:
public void method1()
{
//Method 1
}
public void method2()
{
//Should call this only after calling method1
}
推荐答案
有几种方法可以实现:
代码合同:
如果您使用 Microsoft的代码合同扩展,您可以在method2
If you use Microsoft's Code Contract Extensions, you can set a flag in method1
that you can require in method2
private bool hasRunMethod1 = false;
public void method1()
{
Contract.Ensures( this.hasRunMethod1 );
//Method 1
hasRunMethod1 = true;
}
public void method2()
{
Contract.Requires( this.hasRunMethod1 );
//Should call this only after calling method1
}
与直接在代码中检查hasRunMethod1
相比,代码协定的主要优点是静态检查器可以在编译时检查前提条件.为了提示静态检查器,method1
使用Ensures
定义了后置条件.
The main advantage of code contracts compared to checking hasRunMethod1
directly in your code is that the static checker can check the precondition at compile time. To give a hint to the static checker method1
defines a postcondition with Ensures
.
模板方法:
如果您不想使用代码协定或不能使用它们(例如,如果您的Visual Studio版本不允许它),则可以使用模板方法模式.不过,这可能仅在特定情况下有效:
If you don't want to use code contracts or you can not use them (for example if your version of Visual Studio does not allow it), you can use the template method pattern. That would probably work only in specific scenarios though:
abstract class Base {
private void method1()
{
//Method 1
}
private void method2()
{
//Method 2
}
protected abstract void BetweenMethod1And2();
public void RunTemplateMethod() {
method1();
BetweenMethod1And2();
method2();
}
}
您需要从Base
派生并为中间代码实现BetweenMethod1And2
.
You need to derive from Base
and implement BetweenMethod1And2
for the intermediate code.
私人令牌:
另一种选择是让method1
返回method2
需要的令牌,但只有它可以提供.但是,您需要确保只有method1
可以提供它,例如使用抽象类的私有实现:
Another option would be to let method1
return a token that method2
needs, but that only it can provide. You would though need to make sure that only method1
can deliver it, for example with a private implementation of an abstract class:
abstract class Token {};
class EncapsulatingClass {
private class PrivateToken : Token {};
public Token method1()
{
//Method 1
return new PrivateToken();
}
public void method2( Token token )
{
if ( ( token as PrivateToken ) == null ) {
throw new ArgumentException();
}
//Method 2
}
}
这篇关于在C#中调用method2之前,是否有任何方法可以强制调用method1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!