开放的编程资料库

当前位置:我爱分享网 > C#教程 > 正文

C#表达式

在本文中,我们使用C#中的表达式。

表达式是一个计算值的代码单元。

表达式由操作数和运算符构成。表达式的运算符指示将哪些操作应用于操作数。

C#中有几种类型的表达式:

  • lambda表达式
  • 查询表达式
  • switch表达式
  • 带表达式
  • 内插字符串表达式
  • 表达式体定义
Func<int, int> square = (int x) => x * x;

在赋值的右边,我们有一个函数体表达式。表达式产生一个值。

Console.WriteLine("falcon");

相比之下,语句(例如写入控制台)不会产生值。

C#lambda表达式

lambda表达式是一个未绑定到标识符的匿名函数。lambda声明运算符=>将lambda的参数列表与其主体分开。

int[] vals = { 1, -2, 3, 4, 0, -3, 2, 1, 3 };

var res = Array.FindAll(vals, (e) => e > 0);
Console.WriteLine(string.Join(" ", res));

在示例中,我们从整数数组中过滤掉所有正值。Array.FindAll函数将谓词函数作为第二个参数。使用(e)=>e>0lambda表达式,我们定义了这个谓词。

$ dotnet run
1 3 4 2 1 3

C#查询表达式

查询表达式允许我们在C#中使用查询提取和转换数据。

int[] vals = { -2, 4, 6, -1, 2, 0, 1, -3, -4, 2, 3, 8 };

var evens = 
    from val in vals
    where val % 2 == 0
    select val;

Console.WriteLine(string.Join(" ", evens));

在示例中,我们使用查询表达式来查找数组中的所有偶数值。

$ dotnet run
-2 4 6 2 0 -4 2 8

C#开关表达式

switch表达式提供基于表达式与一组模式的比较的分支控制。与经典的switchkeyword不同,它返回匹配arm的值。

int age = 23;
string name = "Peter";

List<string> colors = new List<string> {"blue", "khaki", "orange"};
var nums = new int[] {1, 2, 3, 4, 5};

Console.WriteLine(check(age));
Console.WriteLine(check(name));
Console.WriteLine(check(colors));
Console.WriteLine(check(nums));

object check(object val) => val switch 
{
    int => "integer",
    string => "string",
    List<string> => "list of strings",
    Array => "array",
    _ => "unknown"
};

在示例中,我们使用switch表达式找出变量的数据类型。

$ dotnet run
integer
string
list of strings
array

C#表达式

with表达式生成其操作数的副本,并修改了指定的属性和字段。

Point p1 = new Point(0, 0);
Point p2 = p1 with { y = 3 };

Console.WriteLine(p1);
Console.WriteLine(p2);

record Point(int x, int y);

在示例中,我们创建了一个点的副本,并将其y成员修改为3。

$ dotnet run
Point { x = 0, y = 0 }
Point { x = 0, y = 3 }

C#内插字符串表达式

我们可以将表达式放入内插字符串中以创建格式化字符串。内插字符串以$字符为前缀。

int x = 5;
int y = 6;

Console.WriteLine($"{x} * {y} = {x * y}");

在示例中,我们创建了一个字符串,其中我们将两个值相乘。

$ dotnet run
5 * 6 = 30

C#表达式主体定义

表达式主体定义为函数、构造函数、属性、索引器或终结器提供简明的定义。

Func<int, int> square = (int x) => x * x;

int r = square(5);
Console.WriteLine(r);

var u = new User("John Doe", "gardener");
Console.WriteLine(u);

class User
{
    public User(string name, string occupation) =>
        (Name, Occupation) = (name, occupation);

    public string Name { get; set; }
    public string Occupation { get; set; }

    public override string ToString() => $"{Name} is a {Occupation}";
}

在程序中,我们有square函数、User构造函数和ToString成员函数的表达式体定义。

$ dotnet run
25
John Doe is a gardener

在本文中,我们使用了C#中的表达式。

列出所有C#教程。

未经允许不得转载:我爱分享网 » C#表达式

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏