我正在尝试编写一个可以表示力和维度的向量类。通常情况下,这不是问题,因为大多数人会创建一个名为“Magnitude”的属性,返回一个双精度浮点型。双精度浮点型并不关心它们所代表的是力还是维度,都能很好地代表。然而,我正在使用这个开源库Unit Class Library来表示维度和力。
以下是我想要实现的代码,是否有办法使属性根据T
返回不同类型(构造函数也是同样的情况)?如果可能,应该如何实现?
public class Vector<T> : LineSegment
{
ForceUnit _magnitudeForce;
/// <summary>
/// Returns the magnitude of the vector (equals the length of the line segment parent if T is Dimension, if T is Force, return variable )
/// </summary>
public T Magnitude
{
get {
Type typeT = typeof(T);
if (typeT == typeof(Dimension))
{
return base.Length;
}
else if (typeT == typeof(ForceUnit))
{
return _magnitudeForce;
}
...
}
我可以使用dynamic
关键字来实现这个目的吗?或者,我应该创建一组接口,然后在Unit Library上使用它们吗?
interface IDistance
{
double Centimeters { get; }
double Feet { get; }
double Inches { get; }
double Kilometers { get; }
double Meters { get; }
double Miles { get; }
double Millimeters { get; }
double Sixteenths { get; }
double ThirtySeconds { get; }
double Yards { get; }
}
interface IForceUnit
{
double Kips { get; }
double Newtons { get; }
double Pounds { get; }
}
然后创建一个Hybrid类,实现这两个类的功能,作为该类的大小。
我管理Unit Class Library,所以欢迎提出在此进行更改的建议。但请记住,该库的直观性和单位转换能力是我想保持的项目价值。
typeof(T)
,那么你的方法/类/属性根本不应该是通用的。 - Sriram SakthivelIUnit
派生出来并且具有一些共同属性(比如它们的值),那么这将是微不足道的。我建议放弃这个单位库,寻找一个更好的。 - John Alexiou