-6

给定两个这样的接口:

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'

任何想法?谢谢。

4

2 回答 2

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()公开,并且接口的名称错误(MyInterfaceX而不是IMyInterfaceX

ideone:http: //ideone.com/WvOnvY

于 2013-08-17T11:03:34.890 回答
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,所以一定有更多的事情发生。

于 2013-08-17T11:02:35.990 回答