2010-02-24 25 views
2

我在C#中重載方法有點麻煩。我有兩個看起來像這樣的方法。當使用字符串和sting時重載方法的問題[]

public static void Sample(string string1, string string2, string string3, 
System.Windows.Forms.MessageBoxButtons buttons) 
{} 
public static void Sample(string string1, string[] string2, string string3, System.Windows.Forms.MessageBoxButtons buttons) 
{} 

當我嘗試調用第二種方法時,出現錯誤「無法將字符串[]'轉換爲'字符串'」。我究竟做錯了什麼?

它適用於重載不使用MessageBoxButtons枚舉的方法,但不適用於此方法。

調用代碼如下所示。

string[] myStringArray = new string[] {"this is a test","of overloaded methods"}; 
Sample("String1",myStringArray,"String2",System.Windows.Forms.MessageBoxButtons.OK); 

編輯: 的問題是在我的構建腳本。在創建引用第一個dll的下一個dll之前,並沒有等待dll被創建,所以在dll中引用的地方做了哪些更改。

猜測這是一個不使用IDE的陷阱。

+0

你可以發佈一個簡短但完整的程序來演示問題嗎? – dtb 2010-02-24 14:44:23

+2

同上。我將這些方法複製到測試應用程序中,然後將它們稱爲無錯誤。可能在通話中發生錯誤,而不是功能。 – xcud 2010-02-24 14:46:23

回答

1

仍然沒有錯誤,當我編譯此:

using System; 

namespace Test 
{ 
    class Program 
    { 
     public static void Sample(string string1, 
      string string2, 
      string string3, 
      System.Windows.Forms.MessageBoxButtons buttons) 
     { } 
     public static void Sample(string string1, 
      string[] string2, 
      string string3, 
      System.Windows.Forms.MessageBoxButtons buttons) 
     { } 

     static void Main() 
     { 
      string[] myStringArray = 
       new string[] { "this is a test", "of overloaded methods" }; 
      Sample("String1", 
       myStringArray, 
       "String2", 
       System.Windows.Forms.MessageBoxButtons.OK); 
     } 
    } 
} 

這個錯誤在您的環境?

1

您沒有顯示調用代碼。我的猜想是你試圖傳遞一個字符串數組作爲第一個或第三個參數而不是第二個參數 - 但是如果你發佈你的代碼(或更好,一個簡短但完整的例子),那麼我們就可以整理出來。

0

沒有看到你是怎麼稱呼它的,很難說,但你需要確保你的第一個和第三個參數是總是字符串,而你最後一個參數的類型是MessageBoxButtons。只有第二個參數可以更改。

0

這可以滿足您的需求嗎?

public static void Sample(MessageBoxButtons buttons, params string[] args) 
{ 
} 
相關問題