从另一个类调用委托方法 [英] Call Delegate methods from another class

查看:90
本文介绍了从另一个类调用委托方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何在 C# 中编写跨类的委托方法调用.我来自 Objective-C 的世界,这可能让我感到困惑.在 Objective-C 中,我可以在子类中分配一个委托对象作为父类(即,childViewcontroller.delegate = self;).然后我可以使用以下方法在委托类中触发一个方法:

I am having trouble figuring out how to program delegate method calls across classes in C#. I am coming from the world of Objective-C, which may be confusing me. In Objective-C, I can assign a delegate object inside a child class, to be the parent class (I.e., childViewcontroller.delegate = self;). Then I can to fire a method in the delegate class by using:

if([delegate respondsToSelector:@selector(methodName:)]) {
   [delegate methodName:parametersgohere];
}

但是,我不知道如何在 C# 中执行此操作.我已经阅读了一些关于 C# 委托的一般内容(例如,在这里),但我还是卡住了.

However, I can't figure out how to do this in C#. I've read a bit about C# delegates in general (for example, here), but I'm still stuck.

有什么例子可以解释这个吗?

Are there any examples that explain this?

这是我的完整场景:我有 classA 实例化 classB 的实例.ClassB 触发一个方法(调用 Web 服务),在响应时,我想触发 classA 中的方法.

Here is my scenario in full: I have classA which instantiates an instance of classB. ClassB fires a method (which call a web service), and upon response, I'd like to fire a method in classA.

是否有任何Hello World"类型的教程可以解释这方面的基础知识?

Any 'Hello World' types of tutorials out there that might explain the very basics of this?

推荐答案

委托是指向方法的对象,无论是静态方法还是实例方法.因此,对于您的示例,您只需使用事件模型:

A delegate is an object that points to a method, be it a static or instance method. So for your example, you would just use the event model:

class Caller {
    public void Call() {
        new Callee().DoSomething(this.Callback); // Pass in a delegate of this instance
    }

    public void Callback() {
        Console.WriteLine("Callback called!");
    }
}

class Callee {
    public void DoSomething(Action callback) {
        // Do stuff
        callback(); // Call the callback
    }
}

...

new Caller().Call(); // Callback called!

Caller 实例将委托传递给 Callee 实例的 DoSomething 方法,后者又调用指向的方法,即Caller 实例的Callback 方法.

The Caller instance passes a delegate to the Callee instance's DoSomething method, which in turn calls the pointed-to method, which is the Callback method of the Caller instance.

这篇关于从另一个类调用委托方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆