【发布时间】:2016-10-05 16:06:55
【问题描述】:
我有一个需要用 void 委托构造的类:
//an object that's constructed with a "void delegate of no params"
public class BindableCommand
{
public delegate void ExecuteMethod();
private readonly ExecuteMethod _executeMethod;
public BindableCommand(ExecuteMethod executeMethod)
{
_executeMethod = executeMethod;
}
}
当它以下列方式构造时,它可以工作:
public class Test
{
public static void Main()
{
//creates a bindable command
BindableCommand b = Create();
}
private static BindableCommand Create(){
BindableCommand b = new BindableCommand(Function);
return b;
}
private static void Function(){}
}
我现在想在构造 BindableCommand 之前将 Function 作为参数传递。
我的尝试编译失败:
public class Test
{
public static void Main()
{
//creates a bindable command
BindableCommand b = Create(Function);
}
private static BindableCommand Create(Action action){
BindableCommand b = new BindableCommand(action);
return b;
}
private static void Function(){}
}
prog.cs(20,19): warning CS0219: The variable `b' is assigned but its value is never used
prog.cs(24,23): error CS1502: The best overloaded method match for `BindableCommand.BindableCommand(BindableCommand.ExecuteMethod)' has some invalid arguments
prog.cs(9,12): (Location of the symbol related to previous error)
prog.cs(24,43): error CS1503: Argument `#1' cannot convert `System.Action' expression to type `BindableCommand.ExecuteMethod'
但我认为Action 是void delegate()?
我不能传递一个无效的委托:
private static BindableCommand Create(delegate void action){/* ... */}
看来我必须做到以下几点:
private static BindableCommand Create(BindableCommand.ExecuteMethod action){/* ... */}
有没有办法让演员自动发生?
【问题讨论】:
-
无法确定stackoverflow.com/questions/7830441/… 是否足够精确重复...
标签: c# function types casting delegates