2012-10-23 45 views
3

Possible Duplicate:
Is it possible to create an extension method to format a string?用的String.Format奇怪的編譯器錯誤的擴展方法

我有這個類:

public class Person 
{ 
    public string Name { get; set; } 
    public uint Age { get; set; } 

    public override string ToString() 
    { 
     return String.Format("({0}, {1})", Name, Age); 
    } 
} 

擴展方法:

public static string Format(this string source, params object[] args) 
{ 
    return String.Format(source, args); 
} 

我想測試它,但我有以下奇怪的行爲:

Person p = new Person() { Name = "Mary", Age = 24 }; 

// The following works 
Console.WriteLine("Person: {0}".Format(p)); 
Console.WriteLine("Age: {0}".Format(p.Age)); 

// But this gives me a compiler error: 
Console.WriteLine("Name: {0}".Format(p.Name)); 

編譯器錯誤:

無法通過對實例的引用訪問成員'string.Format(string,params object [])'。使用類型名稱對其進行限定。

爲什麼?我怎麼解決這個問題?

+1

您應該檢查此http://計算器.com/questions/6587243/is-it-it-possible-to-create-an-extension-method-to-format-a-string及其接受的答案。 –

回答

1

由於p.Name是一個字符串,你必須在第三種情況的曖昧電話:

string.Format(string) 

{string instance}.Format(object[]); 

解析器選擇適合的簽名最好的方法(在你的情況下,一個stringobject[])通過擴展方法。

您可以通過重命名擴展方法解決問題,或者第二個參數鑄造的目的是防止解析器從選擇靜態方法:

Console.WriteLine("Name: {0}".Format((object)p.Name)); 
1

您已經創建了與現有方法具有相同簽名的擴展方法(String.Format)。您需要爲擴展方法使用不同的名稱。而不是像FormatWith(...)那樣。

我站好了。我只是放在一起進行單元測試來驗證此行爲,並且無法調用「某些字符串」.Format(...)。在C#中,編譯器給了我一個「無法在非靜態上下文中訪問靜態方法」格式「。鑑於此,我猜你已經設法混淆了編譯器。

+0

String.Format是String類的靜態方法,p.Name是我的類的屬性。這怎麼能根據方法簽名創建一個錯誤?你能解釋得更好嗎? – Nick

+0

靜態方法不能從實例中調用,因此OP得到的異常。 –

+0

這就是我沒有編譯器的便利。我編輯了我的答案,以反映快速單元測試應該事先告訴我的內容。 –