How to make inline functions in C#

后端 未结 6 450
一向
一向 2020-12-04 07:24

I\'m using Linq To XML

new XElement(\"Prefix\", Prefix == null ? \"\" : Prefix)

but I want to do some computation to the prefix before addi

6条回答
  •  温柔的废话
    2020-12-04 08:15

    Yes, C# supports that. There are several syntaxes available.

    • Anonymous methods were added in C# 2.0:

      Func add = delegate(int x, int y)
      {
          return x + y;
      };
      Action print = delegate(int x)
      {
          Console.WriteLine(x);
      }
      Action helloWorld = delegate // parameters can be elided if ignored
      {
          Console.WriteLine("Hello world!");
      }
      
    • Lambdas are new in C# 3.0 and come in two flavours.

      • Expression lambdas:

        Func add = (int x, int y) => x + y; // or...
        Func add = (x, y) => x + y; // types are inferred by the compiler
        
      • Statement lambdas:

        Action print = (int x) => { Console.WriteLine(x); };
        Action print = x => { Console.WriteLine(x); }; // inferred types
        Func add = (x, y) => { return x + y; };
        
    • Local functions have been introduced with C# 7.0:

      int add(int x, int y) => x + y;
      void print(int x) { Console.WriteLine(x); }
      

    There are basically two different types for these: Func and Action. Funcs return values but Actions don't. The last type parameter of a Func is the return type; all the others are the parameter types.

    There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is Comparison, which is roughly equivalent to Func.

    Func compare1 = (l,r) => 1;
    Comparison compare2 = (l, r) => 1;
    Comparison compare3 = compare1; // this one only works from C# 4.0 onwards
    

    These can be invoked directly as if they were regular methods:

    int x = add(23, 17); // x == 40
    print(x); // outputs 40
    helloWorld(x); // helloWorld has one int parameter declared: Action
                   // even though it does not make any use of it.
    

提交回复
热议问题