2011-07-27 73 views
3

我的問題的一部分在this answer中回答。C#如何解析擴展方法調用?

然而,還有另一種情況:

public class A { } 

public static class ExtendedA 
{ 
    public static void Ext(this A a) { } 
} 

public static class ExtendedB 
{ 
    public static void Ext(this A a) { } 
} 

public static class App 
{ 
    public static void Main() 
    { 
     A a = new A(); 
     a.Ext(); 
    } 
} 

如何在C#編譯器選擇的方法調用?

+2

這是否編譯? – V4Vendetta

+0

@Jamiec:是的,你可以,問題是關於擴展方法,這正是他們的工作方式。 – Ian

+1

我想它不會編譯,因爲這個調用在兩者之間是不明確的。 – Ian

回答

3

如果您嘗試編譯同一命名空間中的所有代碼,您將在a.Ext()上收到編譯器錯誤,並說Ext是無法解析的模糊函數調用。爲了解決這個錯誤,你必須將擴展類移動到不同的命名空間中,並只導入其中的一個,或者將該方法作爲普通的靜態方法調用。

作爲一個直接回答你的問題:C#編譯器沒有選擇。它迫使你去。

2

它沒有 - 如果調用完全是模糊的,你會得到編譯器錯誤CS0121:

The call is ambiguous between the following methods or properties: 'ExtendedA.Ext(A)' and 'ExtendedB.Ext(A)'

2

如果你嘗試自己的代碼,它提供了以下錯誤:

錯誤1呼叫在以下方法或屬性之間不明確:'ConsoleApplication3.ExtendedA.Ext(ConsoleApplication3.A)'和'ConsoleApplication3.ExtendedB.Ext(ConsoleApplication3.A)'c:\ temp \ trash \ ConsoleApplication3 \ ConsoleApplication3 \ Program.cs 28 4 ConsoleApplication3

很清楚編譯器試圖解決正確的調用,就像它會爲重載做的一樣,但最後放棄了,因爲兩種方法導致了模糊性。

所以,它似乎試圖解決就像它重載的方法。

1

您不能添加2個具有相同簽名的擴展函數,因爲這會導致模糊性錯誤,因爲編譯器無法區分使用哪個擴展函數。