Skip to main content
 首页 » 编程设计

c#之像在 java 中一样在 C# 中创建事件

2024年02月13日28birdshome

我在 java 中有一个类,它基本上以异步方式执行搜索,我通过监听器返回结果,我需要在 C# 中编写相同的例程我知道 java 之间存在一些差异,因此无法编写,我我是 c# 的初学者,我至少需要一个视野。

public class Operation { 
 
    private List<Operation.Listener> ListEventResult = new ArrayList<Operation.Listener>();      
    public void Search(String word){         
        try { 
            Thread.sleep(3000); 
        } catch(InterruptedException ex) { 
            Thread.currentThread().interrupt(); 
        } 
        if(ListEventResult.size()>0){ 
            for(Operation.Listener li : ListEventResult){ 
                li.Result("Result for "+word);                   
            } 
        } 
    }    
    public void addEventResult(Listener li){ 
        ListEventResult.add(li); 
    }        
 
    public interface Listener{       
        public void Result(String result); 
    }        
} 
 
public class Program { 
 
    public static void main(String[] args) { 
        // TODO Auto-generated method stub 
 
        Operation op = new Operation(); 
        op.addEventResult(new Operation.Listener() {             
            @Override 
            public void Result(String result) {          
                System.out.println(result); 
            } 
        }); 
        op.Search("Facebook"); 
    } 
} 

请您参考如下方法:

事件和委托(delegate)

C# 中的事件是通过委托(delegate)实现的。发布类定义了一个委托(delegate)。订阅类做了两件事:首先,它创建一个与委托(delegate)签名相匹配的方法,然后它创建一个封装该方法的委托(delegate)类型的实例。引发事件时,将通过委托(delegate)调用订阅类的方法。 处理事件的方法称为事件处理程序。您可以像声明任何其他委托(delegate)一样声明您的事件处理程序。

基于文本的 http://msdn.microsoft.com/en-us/library/orm-9780596521066-01-17.aspx

你不需要像java中那样的事件列表,因为C#自带的事件是作为一个集合来处理的,可以用“+”运算符添加它们

一个简单的 C# 代码示例

class Operation 
{ 
    public delegate void ResultHandler(object Operation, String result); 
    public event ResultHandler Result; 
 
    public void Search(String word) { 
 
        Thread.Sleep(3000); 
        if (Result != null)             
            Result(this, "Result for " + word);             
    } 
} 
 
 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
        InitializeComponent(); 
    } 
 
    private void Form1_Load(object sender, EventArgs e) 
    { 
        Operation op = new Operation(); 
        op.Result += op_Result; 
        op.Search("Facebook"); 
 
    } 
 
    void op_Result(object Operation, string result) 
    { 
        MessageBox.Show(result); 
    }         
}