我正在使用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); }
    

基本上有两种不同的类型:FuncAction.Funcs返回值,但Actions不返回值.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.

.net相关问答推荐

实体框架核心:Azure容器应用程序的执行超时已过期

.NET发布的应用程序运行与开发不同的端口

当 Func 委托需要接口作为参数时,它是如何工作的?

为什么具有可为空值的 struct 的 HashSet 非常慢?

在 C# 中获取 log4net 日志(log)文件

将笔画应用于 WPF 中的文本块

使用 EPPlus 时如何设置列类型

Select 文件夹对话框 WPF

为什么 Interlocked.Exchange 不支持布尔类型?

HashSet 是否保留插入顺序?

如何将时间设置为当天的午夜?

.net 自定义配置如何不区分大小写解析枚举 ConfigurationProperty

react 式扩展使用的好例子

如何将 WebResponse.GetResponseStream 返回转换为字符串?

静态方法继承的正确替代方法是什么?

用 double 替换 int 时的 Visual Studio 长编译

无法加载文件或程序集System.ValueTuple

如何从其十六进制 RGB 字符串创建 System.Drawing.Color?

为什么 !0 是 Microsoft 中间语言 (MSIL) 中的一种类型?

判断数据表中是否包含空值的最佳方法