2016-09-29 29 views
-8

在C#中运行程序时是否可以跳过部分代码?我想运行的程序取决于thecode的值。如果它等于一,我将运行整个程序。如果它等于两个,我将跳过一部分代码。如何跳过C#中的部分代码

if (theCode == 1) 
    //run code 1 to code 3 
if (the code == 2) 
    //run code 2 to 3 
if (the code == 3) 
    //run code 3 only 

code1(Str) 
code1(Str) 
code1(Str) 

code2(Str) 
code2(Str) 
code2(Str) 

code3(Str) 
code3(Str) 
code3(Str) 
+0

尝试> =在您的比较,并把//运行代码{} – kenny

+1

你可以用'goto'关键字,但它的使用不是[推荐](http://stackoverflow.com/questions/11906056/goto-is-this-bad) –

+0

严格地说,你可以使用'goto'和'label',但这被广泛认为是不好的编码习惯。 – Abion47

回答

1
function void Code1(){ //run code1 3 times } 
function void Code2(){ //run code2 3 times } 
function void Code3(){ //run code3 3 times } 

if(theCode == 1 { Code1(); Code2(); Code3(); } 
if(theCode == 2 { Code2(); Code3(); } 
if(theCode == 3 { Code3(); } 
+0

可能想要别人如果 – kenny

3

肯尼说,最简单的方法是使用if块和使用>=比较你的旗帜。

if (theCode >= 1) Code1(); 
if (theCode >= 2) Code2(); 
if (theCode >= 3) Code3(); 
+1

比我的解决方案更好:) –

0

试试下面的代码

if (theCode >= 1) 
{ 
    Code1(); 
} 
if (theCode >= 2) 
{ 
    Code2(); 
} 
if (theCode >= 3) 
{ 
    Code3(); 
}