2013-08-17 2 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!"); } 
} 

... I 다음 코드 스 니펫을 컴파일해야한다고 가정합니다.

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 - _ 정확한 코드 만 게시하십시오. 게시하기 전에 확인하십시오. –

+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을 구현 할 수 없습니다.

Ideone (MyInterfaceX 대신 IMyInterfaceX의)

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()을 공개 깜빡하고 인터페이스의 이름은 틀렸다 : http://ideone.com/WvOnvY

+0

그의 질문은 좋지 않지만'using' 선언에'var'을 사용하면 어떻게 될까요?! –

+0

@JeppeStigNielsen 올바르게 작동합니다. – xanatos

+0

@JeppeStigNielsen var를 사용하여 하나 또는 다른 인터페이스에 대한 모든 변형을 MyClass에 제공합니다. http://ideone.com/cueYt1 – xanatos

관련 문제