[英]Need help using c# delegate function
delegate bool Function(int num);
static Function GreatThan10 = delegate(int n){return n >= 10; }; //there is error
class Program
{
static List<int> Traverse(List<int> myList, Function function)
{
var list = new List<int>();
foreach (var item in myList)
{
if (function(item))
{
list.Add(item);
}
}
return list;
}
When I use c# delegate, I find there is an error.当我使用 c# 委托时,我发现有一个错误。 Also I want to know its delegate whether is the same as php callback function?另外我想知道它的委托是否与 php 回调 function 相同?
I am just learning c# and feel its resource relatively litter than JAVA.我只是在学习 c#,感觉它的资源比 JAVA 相对较少。 I want to learn deeply with books.Are there good books can recommend to me?我想通过书籍深入学习。有好书可以推荐给我吗?
Your delegate
declaration just shows the shape that a function would have to have in order to qualify as an input wherever a Function
exists.您的delegate
声明仅显示 function 必须具有的形状,以便在Function
存在的地方有资格作为输入。 You don't have to declare the Function itself as a delegate.您不必将 Function 本身声明为代表。 It can just be an ordinary Function:它可以只是一个普通的Function:
static bool GreatThan10(int n)
{
return n >= 10;
}
Then you can pass it as an argument to Traverse, for example:然后你可以将它作为参数传递给 Traverse,例如:
var bigNumbers = Traverse(new List<int> {1, 10, 100}, GreatThan10);
You just have to move the GreatThan10 field inside your class Program.您只需在 class 程序中移动 GreatThan10 字段。 The first line of your code is just to define a new delegate that takes an int parameter and returns a bool.代码的第一行只是定义一个新的委托,它接受一个 int 参数并返回一个 bool。 The GreatThan10 instead is a reference of that delegate type, so it must be a member of a class. GreatThan10 是该委托类型的引用,因此它必须是 class 的成员。
You also asked if a delegate is the same as PHP callback functions.您还询问了委托是否与 PHP 回调函数相同。 I would say that a delegate is a type that represents a reference to methods.我会说委托是一种表示对方法的引用的类型。 You declare it with some parameters and with a return type, and you can then create new references of that delegate that points to some methods with the same parameters type and return type.您使用一些参数和返回类型声明它,然后您可以创建该委托的新引用,该引用指向具有相同参数类型和返回类型的某些方法。
Try this solution and you should not have any problems.试试这个解决方案,你应该不会有任何问题。
using System;
using System.Collections.Generic;
delegate bool Function(int n);
class Program
{
static Function GreatThan10 = delegate(int n) { return n > 10; };
static void Main(string[] args)
{
List<int> list = new List<int>();
Traverse(list, GreatThan10);
Console.ReadKey();
}
static List<int> Traverse(List<int> myList, Function function)
{
var list = new List<int>();
foreach (var item in myList)
{
if (function(item))
{
list.Add(item);
}
}
return list;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.