2013-08-17 58 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