简体   繁体   中英

Declare an interface as being implemented by a class

I created a class called MostRecentStack<T> which is a stack that only keeps a certain number of items, dropping the ones at the bottom to make room for new ones. I'd like to have a variable that can store a reference to either a regular ("infinite") stack, or one of my custom type, depending on the circumstances, but C# defines no generic "stack" interface. Normally this wouldn't be a problem, but I'd like System.Collections.Generic.Stack<T> to implement the interface as well.

As long as a class provides the required members, is there any way to, in the interface definition, tell the compiler to consider a class as implementing the interface? I'd like to be able to do this without having to use as or other methods of typecasting.

The exact thing you're asking for isn't possible. However, something like should be very similar to what you want:

public class CompatibleStack<T> : System.Collections.Generic.Stack<T>, IYourStackInterface<T>
{
}

The CompatibleStack is functionally equivalent to System.Collections.Generic.Stack, except it now implements IYourStackInterface.

As long as System.Collections.Generic.Stack has all the right members to implement IYourStackInterface, this should compile fine. And you can pass a CompatibleStack around as an IYourStackInterface without any problems.

No, it is not possible to add new interface to existing class that you don't own. Options:

  • if you get instance of the class via some dependency injection controller you may be able to wrap class with proxy that will implement interface by calling matching methods.
  • you can simply derive from existing class and add interface (if it is not sealed) and start using your class.
  • in your particular case as Baldrick pointed out you can do reverse - derive from existing class and implement interface.
  • you can try to use dynamic to get some duck typing (as both classes will have matching methods) for some performance, readability and strong type cost.

Side note: in general C# does not support duck typing, but there is one case ( foreach ) where implementing interface is not strictly required - just having correct methods on collection is enough to support foreach .

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