我正在使用Linq to XML
new XElement("Prefix", Prefix == null ? "" : Prefix)
但我想在将前缀添加到xml之前对其进行一些计算,比如消除空格、特殊字符、一些计算等等
我不想创建函数,因为这个函数对我的程序的任何其他部分都没有任何帮助,但是这个,那么有没有办法创建内联函数呢??
我正在使用Linq to XML
new XElement("Prefix", Prefix == null ? "" : Prefix)
但我想在将前缀添加到xml之前对其进行一些计算,比如消除空格、特殊字符、一些计算等等
我不想创建函数,因为这个函数对我的程序的任何其他部分都没有任何帮助,但是这个,那么有没有办法创建内联函数呢??
是的,C#支持这一点.有几种可用的语法.
在C#2.0中增加了Anonymous methods个:
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!");
}
Lambdas是C#3.0中的新产品,有两种口味.
表达式lambdas:
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
声明lambdas:
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; };
C#7.0引入了Local functions个:
int add(int x, int y) => x + y;
void print(int x) { Console.WriteLine(x); }
基本上有两种不同的类型:Func
和Action
.Func
s返回值,但Action
s不返回值.Func
的最后一个类型参数是返回类型;其他都是参数类型.
存在名称不同的相似类型,但内联声明它们的语法是相同的.这方面的一个例子是Comparison<T>
,大致相当于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.0 onwards
这些方法可以直接调用,就像它们是常规方法一样:
int x = add(23, 17); // x == 40
print(x); // outputs 40
helloWorld(x); // helloWorld has one int parameter declared: Action<int>
// even though it does not make any use of it.