泛型数学与静态抽象接口成员
C# 11 静态抽象接口成员实现通用数值运算,告别重复重载 · 难度:入门 · +10XP
泛型数学与静态抽象接口成员
C# 11 允许在接口中声明 static abstract 成员,使泛型约束能表达运算符(如 +、-、*)。本教程将创建 INumeric
public interface IAddable<TSelf> where TSelf : IAddable<TSelf>
{
static abstract TSelf operator +(TSelf left, TSelf right);
}
public struct MyInt : IAddable<MyInt>
{
int value;
public static MyInt operator +(MyInt a, MyInt b) => new MyInt { value = a.value + b.value };
}