2017-08-24 71 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。尽管这是非常糟糕的设计。 –