What is the difference between Funclt;string,stringgt; and delegate?(Funclt;string,stringgt; 有什么区别?和委托?)
问题描述
我看到代表有两种形式:
I see delegates in two forms:
A. Func<string, string> convertMethod = lambda
B. public delegate string convertMethod(string value);
我不确定这两者之间的实际区别是什么.他们都是代表吗?我相信第一个会使用 lambda,而第二个必须有一种方法来实际执行工作.我可能也很困惑.
I'm uncertain of what actually the difference between these two are. Are they both delegates? I believe the first one would use a lambda and the second would have to have a method to actually perform the work. I may be confused too.
推荐答案
首先,您的两个示例正在做两件完全不同的事情.第一个是声明一个通用委托变量并为其分配一个值,第二个是定义一个 delegate
类型.更完整的例子是:
First of all, your two examples are doing two totally separate things. The first is declaring a generic delegate variable and assigning a value to it, the second is just defining a delegate
type. Your example, more completely, would be:
public static class Program
{
// you can define your own delegate for a nice meaningful name, but the
// generic delegates (Func, Action, Predicate) are all defined already
public delegate string ConvertedMethod(string value);
public static void Main()
{
// both work fine for taking methods, lambdas, etc.
Func<string, string> convertedMethod = s => s + ", Hello!";
ConvertedMethod convertedMethod2 = s => s + ", Hello!";
}
}
但更重要的是,无论是方法,Func
和 delegate string convertMethod(string)
都能够保存相同的方法定义、匿名方法或 lambda 表达式.
But more to the point, both Func<string,string>
and delegate string convertMethod(string)
would be capable of holding the same method definitions whether they be methods, anonymous methods, or lambda expressions.
至于应该使用哪个,视情况而定.如果您希望您的委托更多地由它接受和返回的内容来定义,那么通用委托是完美的.如果您希望委托有一些特殊的名称,可以更详细地定义委托应该做什么(除了简单的 Action
、Predicate
等),那么始终创建自己的委托一个选项.
As for which you should use, depends on the situation. If you want your delegate to be defined more by what it takes and returns, then the generic delegates are perfect. If you want the delegate to have some special name that gives more definition of what that delegate should do (beyond simple Action
, Predicate
, etc) then creating your own delegate is always an option.
这篇关于Func<string,string> 有什么区别?和委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Func<string,string> 有什么区别?和委托?


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01