2013-08-17 61 views
-5

給出兩個接口,如這些時隱式轉換爲System.IDisposable:無法使用 「使用」

public interface MyInterface1 : IDisposable 
{ 
    void DoSomething(); 
} 

public interface MyInterface2 : IDisposable 
{ 
    void DoSomethingElse(); 
} 

...和實現類是這樣的:

public class MyClass : IMyInterface1, IMyInterface2 
{ 
    public void DoSomething()  { Console.WriteLine("I'm doing something..."); } 
    public void DoSomethingElse() { Console.WriteLine("I'm doing something else..."); } 
    public void Dispose()   { Console.WriteLine("Bye bye!"); } 
} 

...我倒是假設下面的代碼片段應該編譯:

class Program 
{ 
    public static void Main(string[] args) 
    { 
      using (MyInterface1 myInterface = new MyClass()) { 
       myInterface.DoSomething(); 
      } 
    } 
} 

...相反,我總是收到以下錯誤信息:

Error 1 'IMyInterface1': type used in a using statement must be implicitly convertible to 'System.IDisposable' 

任何想法?謝謝。

+3

你肯定你」是否正確輸入了一切?在頂部有'MyInterface1'和'MyInterface2',但稍後有'IMyInterface1'和'IMyInterface2'。 – dasblinkenlight

+3

@ j3d - 請僅發佈_accurate_代碼。在發佈前驗證它。 –

+0

如上所述,我們得到*其他*編譯錯誤,而不是你所描述的錯誤。但是,您在編寫上述類型時,每種接口類型(本身)都可以隱式轉換爲'IDisposable'。 –

回答

2

您應該(也)看到關於Dispose()未公開的編譯器錯誤。

public class MyClass : IMyInterface1, IMyInterface2 
{ 
    public void DoSomething()  { Console.WriteLine("I'm doing something..."); } 
    public void DoSomethingElse() { Console.WriteLine("I'm doing something else..."); } 
    void Dispose()    { Console.WriteLine("Bye bye!"); } 
} 

該類中的Dispose()方法無法實現IDisposable,所以必須有更多的東西怎麼回事。

4

正常工作

public interface IMyInterface1 : IDisposable 
{ 
    void DoSomething(); 
} 

public interface IMyInterface2 : IDisposable 
{ 
    void DoSomethingElse(); 
} 

public class MyClass : IMyInterface1, IMyInterface2 
{ 
    public void DoSomething() { Console.WriteLine("I'm doing something..."); } 
    public void DoSomethingElse() { Console.WriteLine("I'm doing something else..."); } 
    public void Dispose() { Console.WriteLine("Bye bye!"); } 
} 

class Program 
{ 
    public static void Main(string[] args) 
    { 
     using (IMyInterface1 myInterface = new MyClass()) 
     { 
      myInterface.DoSomething(); 
     } 
    } 
} 

你忘記了做Dispose()公衆和接口的名字寫錯了(的IMyInterfaceXMyInterfaceX代替)

Ideone:http://ideone.com/WvOnvY

+0

他的問題很糟糕,但是如果在'using'聲明中使用'var',會發生什麼?! –

+0

@JeppeStigNielsen它工作正常。 – xanatos

+0

@JeppeStigNielsen對MyClass的所有變體,var,對其中一個或另一個接口。 http://ideone.com/cueYt1 – xanatos