Cast to not explicitly implemented interface?

Let's say you define some arbitrary interface:

public interface IInterface {
    void SomeMethod();
}

And let's say there are some classes that happen to have a matching public interface, even though they do not "implement IInterface ". IE:

public class SomeClass {
    public void SomeMethod() {
       // some code
    }
}

Is there nevertheless a way to get an IInterface reference to a SomeClass instance? IE:

SomeClass myInstance = new SomeClass();
IInterface myInterfaceReference = (IInterface)myInstance;

No there is no way to do this. If the type doesn't implement the interface then there is no way to cast to it. The best way to achieve behavior similar to the one you want is to create a wrapper type which provides an implementation of IInterface for SomeClass .

public static class Extensions {
  private sealed class SomeClassWrapper : IInterface {
    private readonly SomeClass _someClass;

    internal SomeClassWrapper(SomeClass someClass) {
      _someClass = someClass;
    }

    public void SomeMethod() {
      _someClass.SomeMethod();
    }
  }

  public static IInterface AsIInterface(this SomeClass someClass) {
    return new SomeClassWrapper(someClass);
  }
}

Then you can make the following call

SomeClass myInstance = new SomeClass();
IInterface myInterface = myInstance.AsIInterface();

如果你有权访问源代码,你总是可以装饰这个类,如果没有,你可以做一个包装:

public class InterfaceWrapper : IInterface
{
    private readonly SomeClass _someClass;

    public InterfaceWrapper(SomeClass someClass) { _someClass = someClass; }

    public void SomeMethod() { _someClass.SomeMethod(); }
}

No. Just because two classes happen to have methods with the same name doesn't mean they abide by the same contract. That's why you define the contract by explicitly implementing the appropriate interface(s).

链接地址: http://www.djcxy.com/p/43726.html

上一篇: Clang静态分析仪对autoreleased发出警告

下一篇: 强制转换为未明确实现的接口?