i have an interface like this example:
Interface IRequest{
List<profile> GetProfiles();
void SetProfile (Profile p);
}
Now, in some logging component, i don't have access to the object implementing the interface, but i want to use the names of the methods in the interface. i can of course type them as a string (copy the method name in a string), but i want to use them strong typed so i don't have to keep the method names and string in sync.
In pseudo code, i would do this:
string s= IRequest.GetProfiles.ToString()
Is this in a way possible?
EDIT:
Maybe i should call it: use the interface like it's an Enum string s= IRequest.GetProfiles.ToString()
Interface methods do not have a body - the body is provided by the "implement" class. On implementation of an interface, you must override all of its methods. Interfaces can contain properties and methods, but not fields/variables. Interface members are by default abstract and public.
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated. It is used to achieve multiple inheritance which can't be achieved by class.
By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes.
In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface.
You can achieve this in two ways:
//If you CAN access the instance
var instance = new YourClass(); //instance of class implementing the interface
var interfaces = instance.GetType().GetInterfaces();
//Otherwise get the type of the class
var classType = typeof(YourClass); //Get Type of the class implementing the interface
var interfaces = classType.GetInterfaces()
And then:
foreach(Type iface in interfaces)
{
var methods = iface.GetMethods();
foreach(MethodInfo method in methods)
{
var methodName = method.Name;
}
}
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