考虑类
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;
}
}
恕我直言:在类型系统级别不应允许将具有默认参数的方法添加到没有参数的委托。为什么允许?
PS您不仅可以在 add { } 访问器中执行此操作,还可以在任何其他地方执行此操作,上面的代码只是示例。