コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】登録されているデリゲートの数を返す拡張メソッド

ソースコード

using System;

public static class MulticastDelegateExtensions
{
    public static int GetLength( this MulticastDelegate self )
    {
        if ( self == null || self.GetInvocationList() == null )
        {
            return 0;
        }
        return self.GetInvocationList().Length;
    }
}

使い方

Action act = null;
Debug.Log( act.GetLength() ); // 0

act += () => {};
Debug.Log( act.GetLength() ); // 1

act += () => {};
act += () => {};
act += () => {};
act += () => {};
Debug.Log( act.GetLength() ); // 5

act = () => {};
Debug.Log( act.GetLength() ); // 1

act = null;
Debug.Log( act.GetLength() ); // 0

関連記事