可以做到
using System;
Action action = new Action(Console.WriteLine);
action(); //will write a empty line
但有没有办法传递带参数的方法,例如
using System;
Action action = new Action(Console.WriteLine("Hello World")); //This doesn't work
action(); //want it to write a line which will say "Hello World"
答案 0 :(得分:3)
试试这个:
Action action = new Action(() => Console.WriteLine("Hello World"));
或如提到@JeroenMostert
Action action = () => Console.WriteLine("Hello World");
答案 1 :(得分:0)
你也可以这样做
Action<int> print = ConsolePrint;
print(10);
static void ConsolePrint(int i)
{
Console.WriteLine(i);
}
或者你也可以这样做
Action<int> print = (i)=> Console.WriteLine(i);
print(10);
答案 2 :(得分:0)
您可以使用这样的通用操作
Action<string> writeLine = Console.WriteLine;
writeLine("hello");