如何静态事件比较,在C#中的非静态事件? [英] How do static events compare to non-static events in C#?

查看:544
本文介绍了如何静态事件比较,在C#中的非静态事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才意识到静态的事件存在 - 我很好奇的人们如何使用它们。我不知道相对比较如何容纳静态还是实例方法。例如,一个静态方法基本上是一个全球性的功能。但我已经对的对象的和我有麻烦在全球范围内他们的思想的实例。



下面的一些代码总是相关联的事件提及它是否有助于解释:

 无效的主要()
{
变种C1 =新C1();
c1.E1 + =()=> Console.WriteLine(E1);
C1.E2 + =()=> Console.WriteLine(E2);
c1.F1();
}

//<<委托>> + D()
公众委托无效D();

// + LT;<事件>> E1
// + LT;<类>><<事件>> E2
// + F()
//<<&不GT;>
//<<火>> E1
//<<火>> E2
公共类C1
{
公共无效F1( )
{
OnE1();
OnE2();
}
公共事件ðE1;
私人无效OnE1()
{
如果(E1!= NULL)
{
E1();
}
}
静态公共事件ðE2;
静态私人无效OnE2()
{
如果(E2!= NULL)
{
E2();
}
}
}


解决方案

很多OOP可以在消息传递的角度来理解。



一个方法调用是由主叫方和被叫(携带参数)的消息,回一个消息与返回值



事件是从源到用户的消息。有这样可能参与两个实例中,一个发送消息和一个接收它



通过一个静态事件,也没有发送的实例(只是一种类型,其可以是或可以不是一类)。还有可以编码为委托的目标收件人实例。


I just realized static events exist - and I'm curious how people use them. I wonder how the relative comparison holds up to static vs. instance methods. For instance, a static method is basically a global function. But I've always associated events with instances of objects and I'm having trouble thinking of them at the global level.

Here some code to refer to if it helps an explanation:

void Main()
{
    var c1 = new C1();
    c1.E1 += () => Console.WriteLine ("E1");
    C1.E2 += () => Console.WriteLine ("E2");
    c1.F1();
}

// <<delegate>>+D()
public delegate void D();

// +<<event>>E1
// +<<class>><<event>>E2
// +F()
//      <<does>>
//          <<fire>>E1
//          <<fire>>E2
public class C1
{
    public void F1()
    {
        OnE1();
        OnE2();
    }
    public event D E1;
    private void OnE1()
    {
        if(E1 != null)
        {
            E1();
        }
    }
    static public event D E2;
    static private void OnE2()
    {
        if(E2 != null)
        {
            E2();
        }
    }
}

解决方案

Much of OOP can be thought of in terms of message passing.

A method call is a message from the caller to the callee (carrying the parameters) and a message back with the return value.

An event is a message from the source to the subscriber. There are thus potentially two instances involved, the one sending the message and the one receiving it.

With a static event, there is no sending instance (just a type, which may or may not be a class). There still can be a recipient instance encoded as the target of the delegate.

这篇关于如何静态事件比较,在C#中的非静态事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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