2012-02-17 112 views

回答

1

因爲C#規範規定:

擴展方法Ci.Mj可享有如果:

·次是一個非通用的非嵌套類

·Mj的名稱是標識符

·Mj適用於 參數作爲上面顯示的靜態方法

·隱式標識,引用或裝箱轉換存在 從expr到第一個參數Mj的類型。

就C#規範而言,用戶定義的轉換運算符不同於隱式引用轉換,並且肯定不同於身份或裝箱轉換。

對於暗示爲什麼:

public static class Extensions 
{ 
    public static void DoSomething(this Bar b) 
    { 
     Console.Out.WriteLine("Some bar"); 
    } 

    public static void DoSomething(this Boo b) 
    { 
     Console.Out.WriteLine("Some boo"); 
    } 
} 

public class Foo 
{ 
    public static implicit operator Bar(Foo f) 
    { 
     return new Bar(); 
    } 
    public static implicit operator Boo(Foo f) 
    { 
     return new Boo(); 
    } 
} 

public class Bar { } 
public class Boo { } 

public class Application 
{ 
    private Foo f; 
    public void DoWork() 
    { 
     // What would you expect to happen here? 
     f.DoSomething(); 

     // Incidentally, this doesn't compile either: 
     Extensions.DoSomething(f); 
    } 
} 

C#不能明確地選擇執行其隱式轉換。

相關問題