检测是否从另一个类设置了事件 - c#

我知道从另一个班级调用一个事件几乎没有任何意义。

但是随后进行一些优化,我发现如果未设置事件,我可以提高性能。

可悲的是C#不允许我这样做

public class A
{
    public event Action Event;

    public bool IsEventSet { return Event != null; }
}

main 
{
   var a = new A();
   var isSet = a.Event == null; //why is this not allowed! I can not understand
   isSet = a.IsEventSet; //this seems like a hack to me!
}

我希望我足够清楚,这是有原因的

是否有一个原因?

谢谢!

参考方案

var isSet = a.Event == null; //why is this not allowed! I can not understand

为什么不允许呢?因为它是event,而不是delegate

在c#中,event只是具有约束的委托。

在意识到您可以将委托视为事件之前,我已经对c#进行了编码多年。具体来说,您可以将任意数量的订阅者附加和分离到一个委托。

以下代码演示了这一点:

using System;

public class A
{
    public event Action Event;

    // You could just use System.Action, but I want the example to be clear
    public delegate void HandlerDelegateType();

    public HandlerDelegateType PublicDelegate;


    public void Fire()
    {
        if(PublicDelegate != null)
        {
            PublicDelegate();
        }
    }
}

public static class MainClass
{
    public static int Main(string[] args)
    {
        var a = new A();

        if(a.PublicDelegate == null)
        {
            Console.WriteLine("a.PublicDelegate is null");
        }

        a.PublicDelegate += () => { Console.WriteLine("First handler fired!"); };
        a.PublicDelegate += () => { Console.WriteLine("Second handler fired!"); };


        a.Fire();

        if(a.PublicDelegate != null)
        {
            Console.WriteLine("a.PublicDelegate is not null");
        }


        return 0;
    }
}

日志输出为

a.PublicDelegate为空

第一名经理被解雇了!

第二名经理被解雇了!

a.PublicDelegate不为null

通过使用event关键字,您明确限制了其使用方式。

限制成员的访问方式是面向对象设计的关键方面。它使您(设计师)可以对如何使用您的类有意见。尽管c#为您提供了此功能,但您可以很高兴地不同意它并公开一个委托而不是一个事件。

现在,我承认“仅是受约束的代表”这一短语过于简化。
实际上,您可以将事件作为公共接口公开给基础委托,如下所示:

private HandlerDelegateType _privateDelegate;

public event HandlerDelegateType PublicEvent
{
    add
    {
        _privateDelegate += value;

    }
    remove
    {
        _privateDelegate-= value;
        if(_privateDelegate == null)
        {
            // Can perform some other action here
            // For example, unsubscribe from a second event source
        }
    }
}

LeetCode题解计算机为什么是基于二进制的?

可以是三进制么?二进制有什么好处?题解:为什么叫电子计算机?算盘应该没有二进制

LeetCode题解统计城市的所有灯泡

这个是我刚毕业的时候,一个真实的面试题,这是一个开放题。题目描述:想办法,将一个城市的所有灯泡数量统计出来。题解:费米估算法1、如果某个城市常驻人口有1000万2、假设每5人居住在一套房里,每套房有灯泡5只,那么住宅灯泡共有1000万只3、假设公众场所每10人共享一只灯泡,那么共有100万只4、主要的这两者相加就得出了1100万只当然实际上这是估算的,具体应…

LeetCode题解黑白圆盘

一个圆盘被涂上了黑白二色,两种颜色各占一个半圆。圆盘以一个未知的速度、按一个未知的方向旋转。你有一种特殊的相机可以让你即时观察到圆上的一个点的颜色。你需要多少个相机才能确定圆盘旋转的方向?题解:可以用一个相机即可

LeetCode题解圆上任取三点构成锐角三角形的概率

来自字节跳动的一道几何题题解:1/4

LeetCode题解深度优先遍历和回溯的关系?

深度优先遍历的范围更大还是回溯的范围更大?为什么?题解:我的理解是:dfs是回溯思想的一种体现- 回溯:是在整个搜索空间中搜索出可行解,在搜索过程中不断剪枝回退,这是回溯的思想,这个搜索空间并没有限制于特定的数据结构。- dfs:dfs是指特定的数据结构中如图,树(特殊的图)中搜索答案,范围限制在了特定的数据结构。个人拙见。