I have a MehtodBase of a method and I need to know if that method is an implementation of a specific interface. So if I have the following class:
class MyClass : IMyInterface
{
public void SomeMethod();
}
Implementing the interface:
interface IMyInterface
{
void SomeMethod();
}
I want to be able to discover at runtime (using reflection) if a certain method implements IMyInterface.
To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
With the aim to make the code robust, i would like to check that the class implements the interface before instantiation / casting. I would like the the keyword 'instanceof' to verify a class implements an interface, as i understand it, it only verifies class type.
Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how.
You can use GetInterfaceMap
for this.
InterfaceMapping map = typeof(MyClass).GetInterfaceMap(typeof(IMyInterface));
foreach (var method in map.TargetMethods)
{
Console.WriteLine(method.Name + " implements IMyInterface");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With