繁体   English   中英

C#:如何使用委托在对象上查找函数并调用它

[英]C#: How can I use delegate to find a function on an object and call it

我想要一个这样的功能:

Event.Call<Interface>(objectWithThatInterface, (x) => x.MethodOnObject);

因此,将在此对象上调用该方法。 但是我不知道该怎么做。 也许与代表有什么关系?

在我看来,这很简单地通过以下方式实现:

public static class Event
{
    public static void Call<T>(T instance, Action<T> method) where T : Interface
    {
        method(instance);
    }
}

我有意避免将任何错误检查,以保持代码的简单,但它可能会抛出空引用异常如果任一参数为null

您可以尝试这样的事情:

实施事件类:

class Event
{
    public static void Call<TInstance>(TInstance instance, Action<TInstance> action)
        where TInstance : IInterface
    {
        // invoke your instance
        action(instance);
    }
}

实施具体课程:

class ConcreteObject
    : IInterface
{
    public void MethodOnObject()
    {
         Console.WriteLine("Called MethodOnObject()");
    }
}

实施接口:

interface IInterface
{
    void MethodOnObject();
}

用法:

IInterface objectWithThatInterface = new ConcreteObject();

Event.Call<IInterface>(objectWithThatInterface, x => x.MethodOnObject());

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM