I would like to have a function like this:
Event.Call<Interface>(objectWithThatInterface, (x) => x.MethodOnObject);
So the method will be called on this object. But I have no idea how to do this. Maybe something with delegates?
It seems to me that this is very simply achieved with this:
public static class Event
{
public static void Call<T>(T instance, Action<T> method) where T : Interface
{
method(instance);
}
}
I have purposely avoided putting in any error checking to keep the code simple, but it should probably throw null reference exceptions if either of the parameters are null
.
You could try something like this:
Implement event class:
class Event
{
public static void Call<TInstance>(TInstance instance, Action<TInstance> action)
where TInstance : IInterface
{
// invoke your instance
action(instance);
}
}
Implement concrete class:
class ConcreteObject
: IInterface
{
public void MethodOnObject()
{
Console.WriteLine("Called MethodOnObject()");
}
}
Implement interface:
interface IInterface
{
void MethodOnObject();
}
Usage:
IInterface objectWithThatInterface = new ConcreteObject();
Event.Call<IInterface>(objectWithThatInterface, x => x.MethodOnObject());
Hope it helps
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.