2015-02-11 72 views
-1

我有一個VB6函數,它具有可選的日期間隔參數,我試圖將其轉換爲C#。我也不確定在代碼中處理這個問題的最佳方法。這裏是VB函數聲明:將VB6可選參數轉換爲C#

Private Function ReplaceDateTextNonBinary(psTable as String, psColumn as String, psColumnOffSet as String, psDateFormat as String, Optional psInterval as String = "n") 

此函數在下面的DateAdd方法調用中使用可選參數。

DateTime = DateAdd(psInterval, oSQL.Value(psColumnOffset), Date$) 

這是我打算如何使用params關鍵字將函數聲明轉換爲C#。

private static bool ReplaceDateTextNonBinary(string psTable, string psColumn, string pColumnOffset, string psDateFormat, params string psInterval) 

我認爲這將工作,但我不知道如何編碼這將採取任何日期間隔作爲字符串。我正在考慮使用switch ... case語句,但這看起來不太優雅。

任何想法。

+0

的C#'params'關鍵字類似於'ParamArray' VB關鍵字,所以它不是你在這裏尋找什麼。 – 2015-02-11 16:27:15

+4

請求幫助之前請使用Google。顯而易見的查詢是「c#可選參數」。採取第一擊。 – 2015-02-11 16:30:37

+0

對不起,發佈重複的問題。我大部分時間都在Google上看,並且一無所獲。我不確定如何更好地分析問題。 – GhostHunterJim 2015-02-11 16:41:59

回答

2

您可以使用C#的可選參數,就像這樣:

private static bool ReplaceDateTextNonBinary(string psTable, 
              string psColumn, 
              string pColumnOffset, 
              string psDateFormat, 
              string psInterval = "n") 

如果可選參數沒有通過,將獲得價值"n"。請注意,可選參數必須在方法簽名中最後列出。另外請注意,這是一個C#4.0特性,不適用於早期版本的C#(在這種情況下,簡單的重載可能是您最好的選擇)。

參見:Named and Optional Arguments (C# Programming Guide)

的4.0之前的方式做這將是這樣的:

private static bool ReplaceDateTextNonBinary(string psTable, 
              string psColumn, 
              string pColumnOffset, 
              string psDateFormat) 
{ 
    return ReplaceDateTextNonBinary(psTable, 
            psColumn, 
            pColumnOffset, 
            psDateFormat, 
            "n"); 
} 

private static bool ReplaceDateTextNonBinary(string psTable, 
              string psColumn, 
              string pColumnOffset, 
              string psDateFormat, 
              string psInterval) 
{ 
    // your implementation here 
}