csharp-语法

循环

while

while(condition)
{
statement(s);
}

for

for (initializer; condition; iterator)
body

for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}

foreach, in

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
count++;
Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

tuple

```

## 定义常量

```c#
static class Constants
{
public const double Pi = 3.14159;
public const int SpeedOfLight = 300000; // km per sec.
}
class Program
{
static void Main()
{
double radius = 5.3;
double area = Constants.Pi * (radius * radius);
int secsFromSun = 149476000 / Constants.SpeedOfLight; // in km
}
}

函数

传参

引用传递:使用 ref, out。
ref 表示传入前是已经初始化的
out 表示传入前不一定初始化,但是传出时一定要赋值。

按引用传参只是为了避免复制,而不需要修改值的情况 使用 in 修饰符

using statement

Provides a convenient syntax that ensures the correct use of IDisposable objects. Beginning in C# 8.0, the using statement ensures the correct use of IAsyncDisposable objects.

msdn

string manyLines=@"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";

using var reader = new StringReader(manyLines);
string? item;
do {
item = reader.ReadLine();
Console.WriteLine(item);
} while(item != null);

nullable value type T?

int?:表示可空类型,就是一种特殊的值类型,它的值可以为null
用于给变量设初值得时候,给变量(int类型)赋值为null,而不是0
int??:用于判断并赋值,先判断当前变量是否为null,如果是就可以赋役个新值,否则跳过

如果基础类型的值为 null,请使用 System.Nullable.GetValueOrDefault 属性返回该基础类型所赋的值或默认值,例如 int j = x.GetValueOrDefault();

请使用 HasValue 和 Value 只读属性测试是否为空和检索值,例如 if(x.HasValue) j = x.Value;

public int? a=null;
public int b()
{
return this.a ?? 0;
}