首先,我不会假设虚拟方法调用会比委托更快。也许它会,也许它不会——但如果性能对你来说真的那么重要,你应该衡量它。使用 lambda 表达式对此进行编码非常简单,特别是如果您要表示的只是一个函数:
public static readonly Func<int, int> Addition = (x, y) => x + y;
public static readonly Func<int, int> Subtraction = (x, y) => x - y;
// etc
(我只是猜测这里的操作,因为我们不知道细节。)
C# 中的子类没有特别小的语法,但对于像这样的半单例,我发现嵌套类工作得很好......类似于 Java 枚举:
public abstract class Primitive
{
public static readonly Primitive Addition = new AdditionPrimitive();
public static readonly Primitive Subtraction = new SubtractionPrimitive();
// Prevent outside instantiation
private Primitive()
{
}
public abstract int Apply(int x, int y);
// Anything else you want
private class AdditionPrimitive : Primitive
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class SubtractionPrimitive : Primitive
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}