Func<string,string> 有什么区别?和委托?

What is the difference between Funclt;string,stringgt; and delegate?(Funclt;string,stringgt; 有什么区别?和委托?)
本文介绍了Func<string,string> 有什么区别?和委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到代表有两种形式:

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!";
    }
}

但更重要的是,无论是方法,Funcdelegate 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.

至于应该使用哪个,视情况而定.如果您希望您的委托更多地由它接受和返回的内容来定义,那么通用委托是完美的.如果您希望委托有一些特殊的名称,可以更详细地定义委托应该做什么(除了简单的 ActionPredicate 等),那么始终创建自己的委托一个选项.

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&lt;string,string&gt; 有什么区别?和委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)