Reputation: 4572
I have an interface
public interface IInputReciever {
void OnRecieveInput(InputInfo Info);
}
and an interface extension class
public static class IInputRecieverExtensions {
public static void SubscribeToInput(this IInputReciever Reciever) {
//Use member of X
}
public static void UnsubscribeFromInput(this IInputReciever Reciever) {
//Use member of X
}
}
Let's say I have two classes A and B; however, while only B inherits from X, both implement my interface.
public class B : X, IInputReciever {
//Contains members of B and X
}
public class A : IInputReciever {
//Contains members of A only
}
In my interface extension I'd like to use the memebers of X, but that will not compile because the implementor is not known to be a subclass of X and also is not guaranteed to be one.
Can I somehow force my implementors to derive from X in order for this scenario to work - or is there a better way for solving this?
Upvotes: 0
Views: 258
Reputation: 1382
You can use a generic method. Thus, you can work with where
.
public static void SubscribeToInput<TInputReciever>(this TInputReciever Reciever) where TInputReciever : IInputReciever, X
{
//Use member of X
}
This will force a Receiver to implement IInputReceiver
and X
, because of the constraints of the generic type arguments.
Upvotes: 3
Reputation: 929
I think you can use generic extension method with constraints:
public static class IInputRecieverExtensions{
public static void SubscribeToInput<T>(this T Reciever) where T : X, IInputReceiver {
//Use member of X
}
public static void UnsubscribeFromInput<T>(this T Reciever) where T : X, IInputReceiver {
//Use member of X
}
}
Upvotes: 1
Reputation: 5313
The point of using an interface is to indicate that you don't care about the implementation details, that is, what class implements the interface. If you must force the derived classes to use a particular implementation, then make X an abstract base class, don't provide an interface, and make your extension method reference X instead of the interface.
Upvotes: 9