如何在C#中的内联函数 [英] How to make inline functions in C#

查看:395
本文介绍了如何在C#中的内联函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用LINQ to XML

I'm using Linq To XML

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

但我想将它添加到XML一样,消除了空格前做一些计算的前缀,特殊字符,一些计算等等

but I want to do some computation to the prefix before adding it to the xml, like eliminating spaces, special chars, some calculations etc

我不希望创建功能,因为这样的人不会有任何帮助我的程序的其他部分,但是这一点,那么,有没有方法来创建内联函数??

I don't want to create functions because this ones won't be of any help on any other part of my program but this, so is there any way to create inline functions??

推荐答案

是的,C#支持。有几个语法可供选择:

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

Func<int, int, int> add = delegate(int x, int y)
                     {
                         return x + y;
                     };
Action<int> print = delegate(int x)
                    {
                        Console.WriteLine(x);
                    }
Action<int> helloWorld = delegate // parameters can be elided if ignored
                         {
                             Console.WriteLine("Hello world!");
                         }


  • 表达的 Lambda表达式(可从C#3起)

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


  • lambda表达式(可从C#3起)

  • Statement lambdas (available from C# 3 onwards)

    Action<int> print = (int x) => { Console.WriteLine(x); };
    Action<int> print = x => { Console.WriteLine(x); }; // inferred types
    Func<int, int, int> add = (x,y) => { return x + y; };
    


  • 基本上有两种不同类型的这些: 函数功能 和的 动作 函数功能的返回值,但动作■不要。的函数功能最后一个类型参数是返回类型;所有其他的参数类型。

    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.

    有类型相似的名称不同,但对于在线声明它们的语法是一样的。这方面的一个例子是 比较< T> ,这大致相当于 Func键< T,T,诠释方式>

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

    Func<string,string,int> compare1 = (l,r) => 1;
    Comparison<string> compare2 = (l,r) => 1;
    Comparison<string> compare3 = compare1; // this one only works from C# 4 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); // helloWord has one int parameter declared: Action<int>
                   // even though it does not make any use of it.
    

    这篇关于如何在C#中的内联函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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