且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有一个C#泛型约束的"实数"类型?

更新时间:2022-12-08 22:15:24

您不能定义这样的约束,但你可以在运行时检查类型。这不会帮助你,虽然做计算。

You can't define such a constraint, but you could check the type at runtime. That won't help you for doing calculations though.

如果你想要做计算,这样的事情将是一种选择:

If you want to do calculations, something like this would be an option:

class Calculations<T, S> where S: Calculator<T>, new()
{
    Calculator<T> _calculator = new S();

    public T Square(T a)
    {
        return _calculator.Multiply(a, a);
    }

}

abstract class Calculator<T>
{
    public abstract T Multiply(T a, T b);
}

class IntCalculator : Calculator<int>
{
    public override int Multiply(int a, int b)
    {
        return a * b;
    }
}

同样的,定义一个 FloatCalculator ,你需要的任何操作。这不是特别快,但比C#4.0 dynamic$c$c>构建。

Likewise, define a FloatCalculator and any operations you need. It's not particularly fast, though faster than the C# 4.0 dynamic construct.

var calc = new Calculations<int, IntCalculator>();
var result = calc.Square(10);

一个副作用是,你将只能够实例计算器如果你传递给它的类型有一个匹配的计算器&LT; T&GT; 执行,这样你就不必做运行时类型检查。

A side-effect is that you will only be able to instantiate Calculator if the type you pass to it has a matching Calculator<T> implementation, so you don't have to do runtime type checking.

这基本上是Hejlsberg为在这次采访那里的问题进行了讨论参照。我个人还是希望看到一些基本类型:)

This is basically what Hejlsberg was referring to in this interview where the issue is discussed. Personally I would still like to see some kind of base type :)