什么是Func键℃之间的差异;字符串,字符串>并委派? [英] What is the difference between Func<string,string> and delegate?

查看:429
本文介绍了什么是Func键℃之间的差异;字符串,字符串>并委派?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到代表有两种形式:

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.

推荐答案

首先,你的两个例子都在做两个完全不同的东西。首先是声明一个泛型委托变量赋值给它,二是刚刚定义委托键入。你的榜样,更彻底,将是:

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键&LT;字符串,字符串&GT; 委托串convertMethod(串)会能够保持同样的方法定义,无论是方法,匿名方法或lambda前pressions。

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.

至于你应该使用它,视情况而定。如果你希望你的委托来进行定义由什么需要和回报越多,那么通用的委托是完美的。如果你想委托有给出该委托应该做的更多的定义(超越了简单的动作 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键℃之间的差异;字符串,字符串&GT;并委派?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆