2017-08-24 70 views
-4

如何跳過c#中特定點的特定代碼? 假設在if條件中,我使用另一個if條件並且我想跳過該條件,而如果條件變爲false,如何在內部跳過較低代碼。那我該怎麼做到呢? 這是我的方案跳過c#中特定點的特定代碼?

if(true) 
{ 
    var discount = GetDicsount(price); 
    if(discount > 100) 
    { 
     //kill here and go away to from main if condition and skip do other work and move to GetType line directly 
    } 
    //Do Other Work 
} 
int type = GetType(20); 
+0

這就是如果這樣做。如果條件不符合,代碼將不會執行。 – HimBromBeere

+0

如果像'if(discount> 100){return; }'。 – mmushtaq

回答

3

你可以顛倒if

if (discount <= 100) { 
    // Do Other Work 
} 

沒有命令,它會從if塊, 打破但是你可以使用goto而是使你的代碼難以效仿。

我認爲這裏真正的問題不是很好的嵌套。

看看嵌套問題,以及如何扁平化你的代碼 所以它變得更容易閱讀和遵循:

https://en.wikibooks.org/wiki/Computer_Programming/Coding_Style/Minimize_nesting http://wiki.c2.com/?ArrowAntiPattern

所以,你的代碼可以看看這個,例如:

var discount = (int?) null; 
if (someCondition) 
{ 
    discount = GetDiscount(price); 
} 

if (discount.Value <= 100) 
{ 
    // Do Other Work 
} 

int type = GetType(20); 
+0

是的,正確的答案是使用goto語句。謝謝 –

+0

@AliNafees - 使用GOTO語句很少**,如果有正確的答案。正確的答案是扁平化嵌套的if語句,因爲這可以降低代碼複雜性,使代碼更具可讀性並減少需要測試的分支的總數。 – Tommy

+0

是的,我只是尋找替代的一些知識... –

2

爲什麼不改變你的邏輯,這樣你扭轉,如果邏輯和做其他工作在那裏?

if(true){ 
    var discount = GetDiscount(price); 
    if(discount <= 100){ 
    //Do Other Work 
    } 
} 
int type = GetType(20); 

請注意,您的外部if語句始終爲true。我假定這只是爲例子,但如果它是實際的代碼,你可以將其刪除:

var discount = GetDiscount(price); 
if(discount > 100) 
{ 
    return; 
} 
//Do Other Work 

如果你真的想你問什麼,你可以看看goto(不推薦)。

if(true) 
{ 
    var discount = GetDiscount(price); 
    if(discount > 100) 
    { 
     goto last; 
    } 
    //Do Other Work 
} 
last: 
int type = GetType(20); 
+0

是的我們可以這樣做,但有沒有辦法像我問過的那樣做? –

+2

@AliNafees已更新。你可以使用goto。儘管這是非常糟糕的設計。 –