是否有一个C#.Net等效于Objective-C的选择器

本文关键字:Objective-C 选择器 有一个 Net 是否 | 更新日期: 2023-09-27 17:57:11

这是一个C#.net问题,适用于同时使用C#.Net的Objective-C开发人员

如你所知,Objective-C可以将方法名称解析为选择器;并且该方法也可以属于外部类

我希望能够在 C#.Net 中使用这种类型的方法,因为它比创建大量事件要干净得多,这些事件可能会变得混乱且难以管理。

如果这是可能的,我该如何实现这一目标?谢谢!

例:

public class Main
{
    public void MyProcess(Callback toMethod)
    {
        // do some fancy stuff and send it to callback object       
        toMethod(result);
    }
}
public class Something
{
    public void RunMethod()
    {
        MyProcess(Method1);
        MyProcess(Method2);
    }
    private void Method1(object result)
    {
        // do stuff for this callback
    }
    private void Method2(object result)
    {
        // do stuff for this callback
    }
}

是否有一个C#.Net等效于Objective-C的选择器

我不知道

Objective-C,但我认为你想要这样的东西:

public class Main
{
    public void MyProcess(Action<object> toMethod, object result)
    {
        // do some fancy stuff and send it to callback object       
        toMethod(result);
    }
}
public class Something
{
    public void RunMethod()
    {
        object result = new object();
        MyProcess(Method1, result);
        MyProcess(Method2, result);
    }
    private void Method1(object result)
    {
        // do stuff for this callback
    }
    private void Method2(object result)
    {
        // do stuff for this callback
    }
}

您必须使用委托。 根据问题中的代码,您将声明一个委托:

public delegate void MethodDelegate(object result);

进程方法的签名更改为以下内容:

public void MyProcess(MethodDelegate toMethod)
{
    // do some fancy stuff and send it to callback object       
    toMethod(result);
}

然后你会调用进程

public void RunMethod()
{
    MyProcess(new MethodDelegate(Method1));
    MyProcess(new MethodDelegate(Method1));
}