2016-04-26 81 views
0

我在問自己是否有可能在方法中使用return的方法只在條件爲真時才執行,但不使用if語句。如果條件爲假,則不會返回任何內容。僅當條件爲真時才返回(不使用if)

爲了更好地理解:

public bool MyMethod() 
{ 
    if (HasErrors()) 
     return HasErrors(); 

    // Some more code 
} 

Some more code將隨後也迴歸東西。我現在想的是這樣的:

public bool MyMethod() 
{ 
    return HasErrorsButReturnsOnlyIfTrue(); 

    // Some more code 
} 

return HasErrorsButReturnsOnlyIfTrue();只需執行,如果HasErrors()返回true。否則,它會被跳過。

如果不使用if,有沒有可能實現類似的目的?

+4

沒有'if'?不需要兩次調用方法?是:'if(hasErrors())返回true;' –

+0

@ Dennis_E'返回hasErrors()'。你爲什麼要'如果(真)返回真'? –

+0

@GuillaumeBeauvois如果它是假的,他不想返回。 –

回答

3

這可能是最接近你會得到:

public bool MyMethod() 
{ 
    return HasErrors() 
     ? true 
     : SomeMoreCode(); 
} 

請注意,這意味着你必須把你的「更多的代碼」在一個單獨的方法,並且該方法現在也必須返回布爾值。

+4

甚至更​​短:'返回HasErrors()|| SomeMoreCode();' –

+0

這並沒有解決:'只有在條件爲真時才返回一些值,但這可能不是OP真正想要的。 –

0

聲明:這只是一個笑話。

public bool MyMethod() 
{ 
    try 
    { 
     return HasErrorsButReturnsOnlyIfTrue(); 
    } 
    catch 
    { 
     // Some more code 
     Console.WriteLine("Test"); 
     return false; 
    } 
} 

public bool HasErrorsButReturnsOnlyIfTrue() 
{ 
    if (some condition) 
     return true; 
    else 
     throw new Exception(); 
} 
+0

哈哈哈:D:D :) – SamGhatak

相關問題