2012-04-18 87 views
1

我怎麼能修改此:返回兩個值

if (reader.GetString(reader.GetOrdinal("Status")) == "Yes") 
{ 
    return true; // Return Status + Date it was Completed 
} 
else 
{ 
    return false; // Return Status + null Date. 
} 

返回兩個值?目前它返回數據庫中的「狀態」列,其值爲「是」或「否」。如何返回已完成日期和狀態?

回答

3
private void DoSomething() { 
     string input = "test"; 
     string secondValue = "oldSecondValue"; 
     string thirdValue = "another old value"; 
     string value = Get2Values(input, out secondValue, out thirdValue); 
     //Now value is equal to the input and secondValue is "Hello World" 
     //The thirdValue is "Hello universe" 
    } 

    public string Get2Values(string input, out string secondValue, out string thirdValue) { 
     //The out-parameters must be set befor the method is left 
     secondValue = "Hello World"; 
     thirdValue = "Hello universe"; 
     return input; 
    } 
+0

非常感謝這麼多!真的很感謝你的指導 – 2012-04-18 18:13:29

+0

能夠做到這一點,謝謝! – 2012-04-18 18:16:40

2

在我看來是最好的方式來做到這一點,爲結果寫一個類或結構。

否則,你可以使用一個外部參數

+0

你能舉出一個實例 – 2012-04-18 17:49:49

+1

爲什麼?類/結構或出參數? – Tomtom 2012-04-18 17:52:02

+0

是沒有辦法返回一個對象,所以在這個呼籲這個我可以做的其他人。 '如果(rtnVal.Status) { lbl.text = rtnVal.CompletedDate }' – 2012-04-18 17:52:17

1

這裏是一個小例子:

private void DoSomething() { 
     string input = "test"; 
     string secondValue = "oldSecondValue"; 
     string value = Get2Values(input, out secondValue); 
     //Now value is equal to the input and secondValue is "Hello World" 
    } 

    public string Get2Values(string input, out string secondValue) { 
     //The out-parameter must be set befor the method is left 
     secondValue = "Hello World"; 
     return input; 
    } 
+0

我不明白怎麼做的出來工作] – 2012-04-18 17:59:33

+1

之前打個電話叫你創造出參數的方法一個新的參數。您使用關鍵字'out'給該函數提供的這個參數。這就像你給對象的參考。在該方法中,您可以使用該參數。離開方法後,參數有一個新值 – Tomtom 2012-04-18 18:01:57

+0

非常感謝!你能告訴我在什麼情況下我們會使用OUT嗎?爲什麼我們只是將其「規範化」爲像具有兩個屬性或某物的對象那樣的常規代碼? – 2012-04-18 18:02:53

1

這也可能是最好的定義struct有兩個屬性,但如果你真的不想要要做到這一點,你可以使用通用KeyValuePair<TKey,TValue>結構:

 KeyValuePair<bool, DateTime?> result; 
     if (reader.GetString(reader.GetOrdinal("Status")) == "Yes") 
     { 
      result = new KeyValuePair<bool, DateTime?> 
       (true, DateTime.Now); // but put your date here 
     } 
     else 
     { 
      result = new KeyValuePair<bool, DateTime?> 
       (false, null); 
     } 
     // reader.Close()? 
     return result; 

KeyValuePair有兩個屬性,KeyValue。關鍵將是你的狀態,價值將是你的日期。

請注意,如果您需要空日期,則需要使用nullable DateTime

+0

我正在查找有關結構的信息,它看起來很有希望,但我需要與他們一起練習。謝謝你的答案。 :) – 2012-04-18 22:37:44