Is there a way to force coercion to call method1 before calling method2 in C #

Hello, this question may be stupid.

But still there is some way to implement the premises as a method for another method. I am using Visual studio (doesn't matter).

Example:

 public void method1()
 {
     //Method 1
 }

 public void method2()
 {
      //Should call this only after calling method1
 }
0
source share
3 answers

There are several ways to achieve this:

Code Contracts:

If you use Microsoft Contract Contract Extensions , you can set the flag to method1, which may be required inmethod2

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, postcondition Ensures.

:

(, Visual Studio ), . , :

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 .

:

method1 , method2, . , method1 , , :

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
    }
}
+3

, - 1 2:

public void method1()
{
    //Method 1
}

public void method2()
{
     method1();
     // The rest of method2 code goes here...
}
+2

, . , , , ( ..) 2 . , .

0

Source: https://habr.com/ru/post/1665225/


All Articles