2013-04-10 59 views
2

很多時候我遇到了一些代碼,我必須返回一個布爾值來指示方法是否成功完成,並在出現問題時顯示帶有錯誤消息的字符串。使用2個返回實現方法的最佳方法是什麼?

我已經通過兩種方式實現了這一點。 第一類包含一類響應,所有類的所有方法都使用此響應類進行通信。例如:

public class ReturnValue { 
    public bool Ok; 
    public string Msg; 
    public object SomeData; 

    public ReturnValue() { 
     this.Ok = true; 
     this.Msg = null; 
    } 

    public ReturnValue(string Msg) { 
     this.Ok = true; 
     this.Msg = Msg; 
    } 

    public ReturnValue(object SomeData) { 
     this.Ok = true; 
     this.SomeData = SomeData; 
    } 

    public ReturnValue(bool Ok, string Msg) { 
     this.Ok = Ok; 
     this.Msg = Msg; 
    } 

    public ReturnValue(bool Ok, string Msg, object SomeData) { 
     this.Ok = Ok; 
     this.Msg = Msg; 
     this.SomeData = SomeData; 
    } 
} 

public class Test { 
    public ReturnValue DoSomething() { 
     if (true) { 
      return new ReturnValue(); 
     } else { 
      return new ReturnValue(false, "Something went wrong."); 
     } 
    } 
} 

的第二種方式是,以具有在錯誤的情況下存儲該消息,並看到消息簡單地調用此方法的方法。例如:

public class Test { 
    public string ReturnValue { get; protected set; } 

    public bool DoSomething() { 
     ReturnValue = ""; 

     if (true) { 
      return true; 
     } else { 
      ReturnValue = "Something went wrong."; 
      return false; 
     } 
    } 
} 

有一種正確的方法可以做到這一點嗎?

+0

您可以返回一個對象數組。 – 2013-04-10 17:21:38

回答

3

而不是依靠一個返回值,要知道如果事情成功了,或者是什麼錯誤,如果它沒有,C#通常依賴於異常,而不是。如果你的程序有效,不要拋出異常。如果不起作用,則拋出異常並將錯誤消息包含在拋出的異常中。

+0

我一般都同意,除非你想向用戶顯示本地化的錯誤信息。如果您將異常消息本地化,那麼可以,如果沒有,則會出現問題。它也可能是一個痛苦的序列化Web調用異常消息。 – 2013-04-10 16:31:55

+0

@MthetheWWatson如果你需要處理這個需求,你總是可以創建你自己的類型的異常,知道如何改變它的錯誤信息的本地化。 – Servy 2013-04-10 16:33:14

+0

因此,所有對該方法的調用都應該包含在try catch塊中? – 2013-04-10 16:47:54

0

個人而言,我更喜歡使用ref關鍵字。

public bool DoSomething(ref string returnValue) { 
    returnValue = "something"; 
    return true; 
} 


string returnValue = ""; 
DoSomething(ref returnValue); 
// returnValue now has new value. 
+0

在這種情況下,它應該不是'ref',因爲該方法不需要讀取值。另外拋出一個異常會比兩種選擇都好。 – Servy 2013-04-10 16:30:18

+0

@Servy好點,這種情況應該是'out',是的,拋出異常很可能是更好的解決方案。 – 2013-04-10 16:31:23

相關問題