public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}
这一小改动让代码更简洁易读。
List<int> numbers = [1, 2, 3, 4, 5];
仿佛施了魔法——敲击键盘更少,代码清晰度倍增。
nameof
优雅重构nameof
运算符让我不再踩坑。它在编译时检查属性名,确保万无一失。public void LogPropertyName()
{
Console.WriteLine(nameof(Person.Name)); // 输出 "Name"
}
现在我已将其奉为圭臬。
string name = person.Name ?? "Unknown";
虽是小改动,却让代码更健壮。
if (person is { Age: > 18, Name: not null })
{
Console.WriteLine($"{person.Name} is an adult.");
}
既简洁又强大。
string message = $"Hello, {person.Name}! You are {person.Age} years old.";
干净到像刚擦亮的镜子。
public (string, int) GetPersonInfo()
{
return ("Alice", 30);
}
var (name, age) = GetPersonInfo();
轻量级且高效。
public void ProcessData()
{
int CalculateSum(int a, int b) => a + b;
Console.WriteLine(CalculateSum(5, 10));
}
逻辑既封装又保持可读性。
using var file = new StreamReader("file.txt");
更简洁,更安全。
IAsyncEnumerable
处理大数据IAsyncEnumerable
让我不再阻塞主线程:public async IAsyncEnumerable<int> FetchDataAsync()
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(100);
yield return i;
}
}
性能与优雅兼得。
(篇幅限制,以下为精简版核心内容展示)
public interface ILogger
{
void Log(string message) => Console.WriteLine(message);
}
public record Person(string Name, int Age);
Span<int> numbers = stackalloc int[10];
int[] numbers = [1, 2, 3, 4, 5];
int lastNumber = numbers; // 5
int[] firstThree = numbers[..3]; // [1, 2, 3]
string? name = null;
string result = person.Age switch
{
> 18 => "Adult",
_ => "Minor"
};
var updatedPerson = person with { Age = 31 };
nameof
妙用[Required(nameof(Person.Name))]
public void Validate(bool condition, [CallerArgumentExpression("condition")] string? message = null)
{
if (!condition) throw new ArgumentException(message);
}
global using System;
namespace MyApp;
public class Person { }
public class Person
{
public required string Name { get; set; }
}
public class Person
{
public string Name { get; init; }
}
public record struct Point(int X, int Y);
public interface IAddable<T> where T : IAddable<T>
{
static abstract T operator +(T a, T b);
}
public void ProcessNumbers(params Span<int> numbers) { }
public ref int GetReference(int[] numbers)
{
return ref numbers[0];
}
[InterpolatedStringHandler]
public ref struct LogInterpolatedStringHandler { }
public void Process<T>(T value) where T : unmanaged { }
[SkipLocalsInit]
public void Process() { }
[ModuleInitializer]
internal static void Initialize() { }
public void Log(string message, [CallerFilePath] string? file = null, [CallerLineNumber] int line = 0)
{
Console.WriteLine($"{file}:{line} - {message}");
}
unsafe void Process(int* pointer) { }
unsafe struct Buffer
{
public fixed int numbers[10];
}
private volatile bool _isRunning;
Span<int> numbers = MemoryMarshal.Cast<byte, int>(buffer);
var pool = ArrayPool<int>.Shared;
int[] array = pool.Rent(10);
pool.Return(array);
public async ValueTask<int> ProcessAsync() { }
public async Task ProcessAsync(CancellationToken token) { }
await Task.Delay(100).ConfigureAwait(false);
await Task.WhenAll(task1, task2, task3);
var completedTask = await Task.WhenAny(task1, task2, task3);
await Task.Run(() => Process());
var tcs = new TaskCompletionSource<int>();
tcs.SetResult(42);
Parallel.ForEach(collection, item => Process(item));
var queue = new ConcurrentQueue<int"];
queue.Enqueue(42);
var list = ImmutableList.Create(1, 2, 3);
var adults = people.Where(p => p.Age > 18).ToList();
Expression<Func<Person, bool>> expr = p => p.Age > 18;
[Generator]
public class MyGenerator : ISourceGenerator { }