“实数"是否有 C# 通用约束?类型? [英] Is there a C# generic constraint for "real number" types?
问题描述
可能的重复:
仅适用于整数的 C# 通用约束
你好!
我正在尝试在 C# 中设置笛卡尔坐标系,但我不想将自己的坐标值限制为任何一种数值类型.有时它们可能是整数,有时它们可能是有理数,这取决于上下文.
I'm attempting to set up a Cartesian coordinate system in C#, but I don't want to restrict myself to any one numerical type for my coordinate values. Sometimes they could be integers, and other times they could be rational numbers, depending on context.
这对我来说是通用类",但我对如何将类型限制为整数和浮点数感到困惑.我似乎找不到涵盖任何实数概念的课程...
This screams "generic class" to me, but I'm stumped as to how to constrict the type to both integrals and floating points. I can't seem to find a class that covers any concept of real numbers...
public class Point<T> where T : [SomeClassThatIncludesBothIntsandFloats?] {
T myX, myY;
public Point(T x, T y) {
myX = x;
myY = y;
}
}
Point<int> pInt = new Point<int>(5, -10);
Point<float> pFloat = new Point<float>(3.14159, -0.2357);
如果我想要这种程度的自由,当涉及到我的类中的计算、清除布尔值、字符串、对象等时,我是否会选择typeof(T)"噩梦?或者更糟的是,我是否选择为我想要处理的每种类型的数字创建一个类,每个类都具有相同的内部数学公式?
If I want this level of freedom, am I electing for a "typeof(T)" nightmare when it comes to calculations inside my classes, weeding out bools, strings, objects, etc? Or worse, am I electing to make a class for each type of number I want to work with, each with the same internal math formulae?
任何帮助将不胜感激.谢谢!
Any help would be appreciated. Thanks!
推荐答案
你不能定义这样的约束,但你可以在运行时检查类型.但这对您进行计算没有帮助.
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 动态
构造.
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);
一个副作用是,如果您传递给它的类型具有匹配的 Calculator
实现,您将只能实例化 Calculator
,因此您不不必进行运行时类型检查.
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 :)
这篇关于“实数"是否有 C# 通用约束?类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!