Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 匿名委托作为函数参数_C#_Anonymous Delegates - Fatal编程技术网

C# 匿名委托作为函数参数

C# 匿名委托作为函数参数,c#,anonymous-delegates,C#,Anonymous Delegates,我试图将参数传递给函数,它是匿名委托(无输入参数,无返回值) 大概是这样的: private function DoSomething(delegate cmd) { cmd(); } DoSomething(() => { Console.WriteLine("test"); }); 然后,我想用这个函数以这种方式调用函数: DoSomething(delegate { Console.WriteLine("Hooah!"); }); 我想要这种特别的

我试图将参数传递给函数,它是匿名委托(无输入参数,无返回值)

大概是这样的:

private function DoSomething(delegate cmd)
{
     cmd();
}
DoSomething(() => 
{
    Console.WriteLine("test");
});
然后,我想用这个函数以这种方式调用函数:

DoSomething(delegate
{
     Console.WriteLine("Hooah!");
});
我想要这种特别的方式,因为它是易于使用的写作风格


可能吗?

正是出于这种目的,Microsoft在.NET framework中创建了和包装器类。这两个阶级都依赖于政治。如果不需要返回任何结果,只需执行匿名函数,请使用Action:

private void DoSomething(Action action)
{
    action();
}
它可以这样使用:

private function DoSomething(delegate cmd)
{
     cmd();
}
DoSomething(() => 
{
    Console.WriteLine("test");
});
()=>
术语是一个,表示类似于没有参数的
输入正在调用…
。有关详细说明,请参阅文档

如果要返回结果,请使用Func委托:

private T DoSomething<T>(Func<T> actionWithResult)
{
    return actionWithResult();
}

.NET内置了很多这样的功能<代码>操作是无参数和无返回类型所需的操作:

private function DoSomething(Action cmd)
{
    cmd();
}
如果希望委托具有参数但没有返回类型(例如,对于接受两个int且没有返回的方法,
Action
),则还有一个通用版本的操作


Func
Predicate
(以及它们的通用版本)也存在。

确保这是可能的。对于没有返回类型的方法,请使用
Action
否则
Func

就这样说吧

Function(() => System.Console.WriteLine("test"));

使用lambdas而不是
delegate
关键字更令人愉快。您甚至可以使用
action.Invoke()
执行操作,但在我看来,最好像调用方法一样调用它,实际上就是这样。

无论如何描述最可能的解决方案,我只想添加关于关键字delegate的内容

  • 第一种情况是-声明新类型:
在本例中,它用于描述输入参数

private function DoSomething(delegate cmd)
{ 
     cmd();
}
但它可以用于声明用于包含函数指针的对象类型:

public delegate *returnParameterType* NewTypeName(*inputParamType1* inputParam1, ...)
然后将该NewTypeName用作输入参数的类型:

private function DoSomething(NewTypeName cmd)
    { 
         cmd();  
    }
  • usinf关键字“delegate”的第二种情况与您的示例类似-声明匿名方法

    代表() { 控制台。WriteLine(“呼啊!”); }


然而,在这种情况下,必须将这种方法分配给合适的已定义的委托,或者分配给类似于泛型委托的操作,因为操作不应该有输出参数

private void delegate Output();
Output func = delegate(){Console.WriteLine("Hooah!");}

检查代理如何用作功能参数可能重复
Function(() => System.Console.WriteLine("test"));
private function DoSomething(delegate cmd)
{ 
     cmd();
}
public delegate *returnParameterType* NewTypeName(*inputParamType1* inputParam1, ...)
private function DoSomething(NewTypeName cmd)
    { 
         cmd();  
    }
private void delegate Output();
Output func = delegate(){Console.WriteLine("Hooah!");}
Action func1 = delegate(){Console.WriteLine("Hooah!");}