参数中有参数的方法

Method With Parameter In Parameter

我想像这样在参数中传递一个参数的方法。但是还是报错,不知道怎么办。

void WriteInScreen(string text){
    Console.WriteLine(text);
}
void WriteInScreen10Times(string text){
    for (int i = 1; i <= 10; i++){
        Console.WriteLine(text);
    }
}
void CallWriteInScreen(Action Method) {
    Method();
}
void StartCall(){
    //Error: Argument 2: Can't not convert from void to System.Action
    CallWriteInScreen(WriteInScreen("Hello!"));
    CallWriteInScreen(WriteInScreen10Time("Hi!"));
}

这只是我的测试代码,我需要解决这个问题才能继续开发我的程序。

你不能这样做

CallWriteInScreen(WriteInScreen10Time("Hi!")); 

因为你定义的方法:WriteInScreen10Time("Hi!") returns void 因此您会将 void 传递给 CallWriteInScreen 方法,该方法需要一个 Action 作为参数

CallWriteToScreen 只接受不接受任何参数且不产生任何结果的委托(a.k.a 和 Action)。不确定是否要创建接受参数化 ActionCallWriteToScreen 方法族:

void CallWriteInScreen(Action Method) {
    Method();
}
void CallWriteInScreen<T1>(Action<T1> Method, T1 arg1) {
    Method(arg1);
}
void CallWriteInScreen<T1, T2>(Action<T1, T2> Method, T1 arg1, T2 arg2) {
    Method(arg1, arg2);
}
void StartCall(){
    CallWriteInScreen(WriteInScreen, "Hello!");
    CallWriteInScreen(WriteInScreen10Time, "Hi!");
}

或者只是想结束最终的方法调用:

void StartCall(){
    CallWriteInScreen(() => WriteInScreen("Hello!"));
    CallWriteInScreen(() => WriteInScreen10Time("Hi!"));
}