很多時候我遇到了一些代碼,我必須返回一個布爾值來指示方法是否成功完成,並在出現問題時顯示帶有錯誤消息的字符串。使用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;
}
}
}
有一種正確的方法可以做到這一點嗎?
您可以返回一個對象數組。 – 2013-04-10 17:21:38