简体   繁体   中英

C#: Can I extend a foreign class such that it implements a local interface

I have 2 assemblies( foreign and local ). The foreign assembly cannot be modified. I would like to extend a foreign class such that it will now implement a local interface. Is this possible in C#?

EDIT: I know that I can do the following:

// foreign.dll
namespace DX {
    public struct Vector3 {
        ...
    }
}

// local.dll
namespace MyDX {
    public static class Extensions {
        public static void MyExtensionMethod( this Vector3 vec, int index ){
            ...
        }
    }
}

What I'm interested in doing is forcing the foreign class/struct to implement a particular interface (without using inheritance ). I would like to use Vector3 as a type in a generic class:

public class MyGeneric<T> where T: IComparable<T> {
    T _value;
}

The above struct: Vector3 does not implement IComparable but I would like to use reflection to implement the interface so that I can use the foreign class/struct in its existing form (ie. w/o using inheritance). Inheritance may be necessary...

Can I extend a foreign class such that it implements a local interface

Sure, provided that the foreign class is not sealed. (And, of course, accessible to the local project, and so on.)

// Foreign.DLL
namespace F 
{ 
  public class B 
  {
    public void Foo() { }
  }
}

// Local.DLL
interface IFooBar 
{ 
  void Foo();
  void Bar();
}
class D : F.B, IFooBar
{
  public void Bar() { }
}

There, D has extended FB , as required, and D implements IFooBar , as required. Notice how FBFoo meets the contractual obligation of IFooBar even though it is on the base class.

If the foreign class is sealed then you'll have to use composition rather than inheritance.

However, I agree with the commenter that says that this smells like an XY problem. Can you say what problem you are really trying to solve, in more detail? Because there might be a better way to accomplish what you want.

In the narrow sense (like extension methods ), extension interfaces are currently not supported by the C# language. But in a wider sense, you can use inheritance or composition as explained in @Eric's answer.

Supporting extension interfaces in C# has been briefly discussed in 2015 in Roslyn issue 3357 . However, this can't be fully implemented by the C# compiler alone, as it requires CLR support to ensure reference equality between (ITheAddedInterface)x and x . The topic seems to be abandoned for now.

Other CIL languages such as F# have a much more flexible extension mechanism than C#. But C# is catching up, as seen eg in C# language issue no. 164 , and the video A Preview of C# 8 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM