C# 作为参数传递带有参数的方法的快捷方式?
让我先说一句,我对C#相当生疏。也就是说,我正在寻找一种方法来传递一个参数为参数的方法。理想情况下,我想做的是:C# 作为参数传递带有参数的方法的快捷方式?,c#,methods,parameters,C#,Methods,Parameters,让我先说一句,我对C#相当生疏。也就是说,我正在寻找一种方法来传递一个参数为参数的方法。理想情况下,我想做的是: static void Main(string[] args) { methodQueue ( methodOne( x, y )); } static void methodOne (var x, var y) { //...do stuff } static void methodQueue (method parameter) { //...wait
static void Main(string[] args)
{
methodQueue ( methodOne( x, y ));
}
static void methodOne (var x, var y)
{
//...do stuff
}
static void methodQueue (method parameter)
{
//...wait
//...execute the parameter statement
}
有人能给我指出正确的方向吗?您可以传递一个参数化方法,该方法使用。 然后,您可以这样做:
公共图书馆
{
MethodQueue(MethodOne);
}
公共无效方法一(整数x,整数y)
{
//做事
}
公共void方法队列(操作方法)
{
//等等
方法(0,0);
}
如果方法需要返回值,也可以使用委托。
//使用操作
使用制度;
使用System.Windows.Forms;
公共类测试1
{
公共静态void Main()
{
行动目标;
if(Environment.GetCommandLineArgs().Length>1)
messageTarget=ShowWindowsMessage;
其他的
messageTarget=Console.WriteLine;
messageTarget(“你好,世界!”);
}
私有静态void ShowWindowsMessage(字符串消息)
{
MessageBox.Show(message);
}
}
这应该是您想要的。它实际上是在向函数传递一个无参数的medthod,但是delegate(){methodOne(1,2);}正在创建一个匿名函数,该函数使用适当的参数调用methodOne
我想在输入它之前测试它,但是只有.NETFramework2.0,这就是我的方法
public delegate void QueuedMethod();
static void Main(string[] args)
{
methodQueue(delegate(){methodOne( 1, 2 );});
methodQueue(delegate(){methodTwo( 3, 4 );});
}
static void methodOne (int x, int y)
{
}
static void methodQueue (QueuedMethod parameter)
{
parameter(); //run the method
//...wait
//...execute the parameter statement
}
您也可以使用纯C替代的函数指针,但这可能会有点混乱,尽管它工作得非常出色。使用lambda语法,这几乎总是最简洁的方法。注意,这在功能上等同于匿名委托语法
class Program
{
static void Main(string[] args)
{
MethodQueue(() => MethodOne(1, 2));
}
static void MethodOne(int x, int y)
{...}
static void MethodQueue(Action act)
{
act();
}
}
我的问题的所有答案都足够了,但你的答案帮助代表们点击我的答案,所以我接受了你的答案。谢谢大家。
public delegate void QueuedMethod();
static void Main(string[] args)
{
methodQueue(delegate(){methodOne( 1, 2 );});
methodQueue(delegate(){methodTwo( 3, 4 );});
}
static void methodOne (int x, int y)
{
}
static void methodQueue (QueuedMethod parameter)
{
parameter(); //run the method
//...wait
//...execute the parameter statement
}
class Program
{
static void Main(string[] args)
{
MethodQueue(() => MethodOne(1, 2));
}
static void MethodOne(int x, int y)
{...}
static void MethodQueue(Action act)
{
act();
}
}