c# 入门语法
一、关于元组
(string name, int age) customer = GetCustomer(); var name = customer.name;
var age = 123;
var name = "aa";
var tuple = (age, name); //元组直接用一样的名字
var anon = new { age, name };
tuple.age = 12;
tuple.name = "bb";
// 用元组可以不用写对象
var t1 = (a: 1, b: 2);
二、关于属性
private int Age { get; }
// 没必要写
private int age; public int Age { get { return age; } }
三、模板字符串
var str = $"prefix {someValue} suffix";
四、switch要写default
简化 switch
switch (x) { case 1: return 1 * 1; case 2: return 2 * 2; default: return 0; }
return x switch { 1 => 1 * 1, 2 => 2 * 2, _ => 0, };
五、哈希码
// 建议用Combine public override int GetHashCode() { return System.HashCode.Combine(base.GetHashCode(), j); }
六、用nameof
var n2 = nameof(Int32);
七、判空
var v = x ?? y; // x不为空就用x,否则就用y
var v = o?.ToString();
if (value is null) return;
八、变量
var obj = new Customer(); // 用var
九、方法
public int GetAge()
{
return this.Age;
}
简化方法:
public int GetAge() => this.Age;
// 注意方法在编写时候 public static ComplexNumber operator + (ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); }
// 建议去掉花括号和return
public static ComplexNumber operator + (ComplexNumber c1, ComplexNumber c2) => new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
// 索引器属性
public T this[int i] { get { return _values[i]; } }
// 建议修改
public T this[int i] => _values[i];
// 避免 as
if (o is int i)
{
// 直接用i 就可以了
// ...
}
var x = i is default(int) or > (default(int)); var y = o is not C c;
int i; if (int.TryParse(value, out i) {...}
if (int.TryParse(value, out int i) {...}
// 使用默认值
void DoWork(CancellationToken cancellationToken = default) { ... }
// 解构
var (name, age) = GetPersonTuple();
// 使用
string[] names = { "Archimedes", "Pythagoras", "Euclid" };
var index = names[names.Length - 1];
// 有个简化语法 var index = names[^1];
string sentence = "the quick brown fox"; var sub = sentence.Substring(0, sentence.Length - 4);
var sub = sentence[0..^4];