我在 C# 中定义物理单元,使用通用结构,在出现错误之前一切正常:
One of the parameters of a binary operator must be the containing type
当试图重载数学运算符以便它们在不同单位之间进行转换时。所以,我有这样的东西:
public interface ScalarUnit { }
public class Duration : ScalarUnit { }
public struct Scalar<T> where T : ScalarUnit
{
public readonly double Value;
public Scalar(double Value)
{
this.Value = Value;
}
public static implicit operator double(Scalar<T> Value)
{
return Value.Value;
}
}
public interface VectorUnit { }
public class Displacement : VectorUnit { }
public class Velocity : VectorUnit { }
public struct Vector<T> where T : VectorUnit
{
#...
public static Vector<Velocity> operator /(Vector<Displacement> v1, Scalar<Duration> v2)
{
return new Vector<Velocity>(v1.Magnitude / v2, v1.Direction);
}
}
+
没有任何错误和 -
运算符,我正在处理 Vector<T>
,但是当我用一个单位代替 T
时,突然就不喜欢了。有什么办法可以做到这一点吗?
我认为它会起作用,因为 Displacement
实现 VectorUnit
界面,我有where T : VectorUnit
在结构头中。我至少在正确的轨道上吗?我是 C# 的新手,所以有时我很难理解发生了什么。
最佳答案
我认为运算符不能通用。
我可能会考虑在运算符中对类型进行硬编码,即如果 typeof(T).GetGenericParameters()[0] 是这个或那个类型等等。
我什至更喜欢的另一种方法是在所有返回 double 值的子类中实现一个公共(public)接口(interface)/基类,然后从运算符将其转换为该接口(interface)/b。类并获取要计算的值。
注:作者convention ,接口(interface)名称应始终以 I
开头(例如:IScalarUnit
)。
关于c# - 泛型的泛型结构 : can I create overloads for specific kinds(? 中的运算符重载)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4643481/