- methods
- user-defined operators
- type conversions
- read-only properties
- indexers
public class RgbColor(int r, int g, int b)
{
public int Red { get; } = r;
public int Green { get; } = g;
public int Blue { get; } = b;
public string ToHex() =>
string.Format("#{0:X2}{1:X2}{2:X2}", Red, Green, Blue);
public static RgbColor operator - (RgbColor color) =>
new RgbColor(
color.Red ^ 0xFF,
color.Green ^ 0xFF,
color.Blue ^ 0xFF
);
}
用於「方法」的例子:
public string ToHex() => string.Format("#{0:X2}{1:X2}{2:X2}", Red, Green, Blue);
public override string ToString() => this.Name;
用於「user-defined operators」的例子:
public static RgbColor operator - (RgbColor color) =>
new RgbColor(
color.Red ^ 0xFF,
color.Green ^ 0xFF,
color.Blue ^ 0xFF
);
public static Complex operator +(Complex a, Complex b) => a.Add(b);
用於「read-only property」的例子:
特別注意,這是 Read Only Property 而不是 Field
public string ID => Guid.NewGuid().ToString();
又一個例子:public class Point(int x, int y) {
public int X => x;
public int Y => y;
public double Dist => Math.Sqrt(x * x + y * y);
public Point Move(int dx, int dy) => new Point(x + dx, y + dy);
}
用於「type conversions」的例子:實現 string 和 Name 之間的隱性轉換
public static implicit operator string(Name n) => n.First + " " + n.Last;
用於「indexers」的例子:
public Customer this[Id id] => store.LookupCustomer(id);