【发布时间】:2013-03-23 13:51:41
【问题描述】:
考虑类
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;
}
}
恕我直言:在类型系统级别不应允许将具有默认参数的方法添加到不带参数的委托。 为什么是允许的?
P.S. 您不仅可以在 add { } 访问器中执行此操作,还可以在任何其他地方执行此操作,上面的代码只是示例。
【问题讨论】:
-
我已经尝试了您的代码,编译器在 a.Test += TestMethod 行上抛出一个错误,指出它是不允许的,因为 TestMethod 与委托 System.Action 不匹配。你确定你的代码可以编译吗?
-
你不能编译那个? pastie.org/7277752
-
不,那不会编译。我正在使用 Visual Studio 2012,我收到编译错误“'TestMethod' 没有重载匹配委托'System.Action'”。将事件声明更改为公共事件 Action
TestEvent 可修复编译错误。 -
嗯,我正在使用 MonoDevelop,所以也许它只是单声道错误/功能。