Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否可以在C中重置方法?_C# - Fatal编程技术网

C# 是否可以在C中重置方法?

C# 是否可以在C中重置方法?,c#,C#,我想知道是否可以从方法本身重置方法。也就是说,如果我有一个从第10行到第30行的方法。是否存在从第30行到第10行并重置值的方法?我不需要这样做,但如果可以的话,这对我的程序很有用 对不起,如果我的英语令人困惑。我不是以英语为母语的人。一个简单的解决方案是,你可以将你的方法分成两种不同的方法。例如,可以在新方法中移动第10行到第30行,并在主方法中调用它 public void MethodA() { ... MethodB(); ... } public void Met

我想知道是否可以从方法本身重置方法。也就是说,如果我有一个从第10行到第30行的方法。是否存在从第30行到第10行并重置值的方法?我不需要这样做,但如果可以的话,这对我的程序很有用


对不起,如果我的英语令人困惑。我不是以英语为母语的人。

一个简单的解决方案是,你可以将你的方法分成两种不同的方法。例如,可以在新方法中移动第10行到第30行,并在主方法中调用它

public void MethodA()
{
  ...

  MethodB();  

  ...
}

public void MethodB()
{
  int a = 0, b = -1;
  string x = string.Empty;
  ...
}
如您所见,在方法B中,值被重置

public void SomeMethod( int someParam, int execTimes )
{
    while( execTimes-- > 0 ) // will decrease execTimes and execute until execTimes < 1
    {                        // mind that the postfix -- operator will first check > 0, then decrease.
                             // so, it's for example 3 > 0, 2 > 0, 1 > 0, 0 !> 0 => 3 iterations.
       // you can init a local var with the parameter from outside.
       int localParam = someParam;
       // doYourStuff here, for example mutate localParam
       localParam += 20;
       // in next iteration, localParam will be reset to someParam value.

       // a var declared in this loop's scope will always be reset to
       // its initial value in each iteration:
       int someStartValue = 0;

       // ... some logic mutating someStartValue;
    }
}
请注意,上面的示例使用了一个动作委托,以展示Fred回答的一些不同方法,当然,这也是有效的。 在这里,您也可以对不同的逻辑使用Repeater方法,从而减少代码中的重复。如果你只需要一种方法,我会选择弗雷德的

作为参考,您可以从中了解这项工作的原因:

而且: 辅导的
如果你是80年代的粉丝,你可以使用goto语句,但是它会让大多数代码审查失败,并且会让你的朋友嘲笑你只是为了教育:有一个goto语句可以做到这一点,而且它以前就被使用过。不幸的是,它保存在C中,但从未使用goto!因为代码会变得难以阅读。您应该使用loopsor,或者像@John提到的那样使用递归。@John遗憾地说is@dan1st我认识的大多数C开发人员都宁愿不这样做。@dan1st我不想滥发这个问题,但我认为我们不需要争论哪一个更糟糕。它们都是恐龙时代的怪物。
public void ExecNTimes( Action thingToDo, int execTimes )
{
    while( execTimes-- > 0 ) thingToDo();
}

public void Logic(int parameter)
{
   // your logic, will always start with same parameter value
}

public void Caller()
{
   ExecNTimes( () => Logic(5), 3 ); // parameter = 5, execute 3x
}