-1

クラスを考慮する

class FirstClass 
{
    //Some fields, ctors and methods
    ...
    public event Action Test
    {
        add
        {
            var method = value.Method;
            var parameters = method.GetParameters (); //Count == 1
            // (1)
            //I don't know anything about value so I think I can pass null as argument list because it's Action, not Action<T>
            //And we get Reflection.TargetParameterCountException here.
            method.Invoke (value.Target, null); 
            //Instead of calling Invoke as done above, we should call it like that:
            // (2)
            method.Invoke (value.Target, new object[] { null });
            //But since it's Action, we should be able to call it with (1) not with (2)
        }
        remove
        {
            ...
        }
    }
}

そして別のクラス

class SecondClass
{
    public void TestMethod (Action action = null)
    {
        ...
    }
    public void OtherMethod ()
    {
        var a = new FirstClass ();
        a.Test += TestMethod;
    }
}

IMHO: パラメータなしでデリゲートにデフォルト引数を持つメソッドを追加することは、型システムレベルでは許可されるべきではありません。なぜそれが許されるのですか?

PS add { } アクセサーだけでなく、他の場所でもこれを行うことができます。上記のコードは単なる例です。

4

1 に答える 1