F# の測定単位に触発され、C# ではできないと (ここで)断言しているにもかかわらず、私は先日、いじっていたアイデアを思いつきました。
namespace UnitsOfMeasure
{
public interface IUnit { }
public static class Length
{
public interface ILength : IUnit { }
public class m : ILength { }
public class mm : ILength { }
public class ft : ILength { }
}
public class Mass
{
public interface IMass : IUnit { }
public class kg : IMass { }
public class g : IMass { }
public class lb : IMass { }
}
public class UnitDouble<T> where T : IUnit
{
public readonly double Value;
public UnitDouble(double value)
{
Value = value;
}
public static UnitDouble<T> operator +(UnitDouble<T> first, UnitDouble<T> second)
{
return new UnitDouble<T>(first.Value + second.Value);
}
//TODO: minus operator/equality
}
}
使用例:
var a = new UnitDouble<Length.m>(3.1);
var b = new UnitDouble<Length.m>(4.9);
var d = new UnitDouble<Mass.kg>(3.4);
Console.WriteLine((a + b).Value);
//Console.WriteLine((a + c).Value); <-- Compiler says no
次のステップは、変換を実装することです (スニペット):
public interface IUnit { double toBase { get; } }
public static class Length
{
public interface ILength : IUnit { }
public class m : ILength { public double toBase { get { return 1.0;} } }
public class mm : ILength { public double toBase { get { return 1000.0; } } }
public class ft : ILength { public double toBase { get { return 0.3048; } } }
public static UnitDouble<R> Convert<T, R>(UnitDouble<T> input) where T : ILength, new() where R : ILength, new()
{
double mult = (new T() as IUnit).toBase;
double div = (new R() as IUnit).toBase;
return new UnitDouble<R>(input.Value * mult / div);
}
}
( static を使用してオブジェクトをインスタンス化することは避けたかったのですが、ご存知のように、インターフェイスで static メソッドを宣言することはできません) 次に、次のようにします。
var e = Length.Convert<Length.mm, Length.m>(c);
var f = Length.Convert<Length.mm, Mass.kg>(d); <-- but not this
明らかに、F# の測定単位と比較すると、これには大きな穴があります (解決してもらいます)。
ああ、質問です。これについてどう思いますか? 使う価値はありますか?他の誰かがすでにうまくやったことがありますか?
この分野に興味のある人向けの更新情報です。別の種類のソリューションについて説明している 1997 年の論文へのリンクを次に示します (特に C# 向けではありません)。