有人可以解释此C#lambda语法? [英] Can someone explain this C# lambda syntax?

查看:98
本文介绍了有人可以解释此C#lambda语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我来到后声明为静态方法:

I recently came upon a static method declared as:

public class Foo
{
  public static Func<HtmlHelper, PropertyViewModel, string> Render = (a, b) =>
  {
    a.RenderPartial(b);
    return "";
  };
}



智能感知提示的用法是(例如):

Intellisense suggests the usage is (for example):

string s = Foo.Render(htmlHelper, propertyViewModel);



这似乎那么,下面的是等价的:

It would seem then that the following is equivalent:

public static string Render(HtmlHelper a, PropertyViewModel b)
{
  a.RenderPartial(b);
  return "";
}



A)什么是第一种样式的名称?我意识到这是一个使用lambda表达式;它是被绊倒了我的 = 标志。我不能标记化它;)

A) What is the name of the first style? I realize it's using lambdas; it's the = sign that is tripping me up. I can't tokenize it ;)

B)如果两个代码块的的等价物,什么是使用前者优于受益后者?

B) If the two code blocks are equivalent, what is the benefit of using the former over the latter?

推荐答案

在大多数情况下,他们似乎功能上等同。事实上,你可以绕过正常的方法作为一个变量。

For the most part they seem functionally equivalent. In fact you can pass around a normal method as a variable.

但也有喜欢的是可以重新定义的功能是别的细微的差别。这大概也是不同的,如果你使用反射,如它可能不是在对类方法列表返回。 (不是100%的反射部分确认)

But there are subtle differences like being able to redefine the function to be something else. It is probably also different if you're using reflection, e.g. it probably isn't returned in the list of methods on the class. (Not 100% sure on the reflection part)

传递的方法作为一个变量,以及2号路怎么允许重新定义Func键那会不会是下面显示的可能的,如果它是一个正常的方法。

The following shows passing a method as a variable as well as how the 2nd way allows redefining the Func that wouldn't be possible if it were a normal method.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetFunc());   //Prints the ToString of a Func<int, string>
        Console.WriteLine(Test(5));     //Prints "test"
        Console.WriteLine(Test2(5));    //Prints "test"
        Test2 = i => "something " + i;
        Console.WriteLine(Test2(5));    //Prints "something 5"
        //Test = i => "something " + i; //Would cause a compile error

    }

    public static string Test(int a)
    {
        return "test";
    }

    public static Func<int, string> Test2 = i =>
    {
        return "test";
    };

    public static Func<int, string> GetFunc()
    {
        return Test;
    }
}

这只是让我思考......如果所有方法被宣布这种方式,你可以有真正的第一类函数在C#的。 ..有趣的....

This just got me thinking... if all methods were declared this way, you could have real first class functions in C#... Interesting....

这篇关于有人可以解释此C#lambda语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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