Units of Measure in F# से प्रेरित, और जोरदार (here) के बावजूद कि आप इसे सी # में नहीं कर पाए, मुझे पता था कि दूसरे दिन मैं किसके साथ खेल रहा हूं।सी # में माप की इकाइयां - लगभग
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);
}
}
(मैं, स्थिर का उपयोग करके वस्तुओं instantiating से बचने के लिए पसंद किया है, लेकिन जैसा कि हम सभी जानते हैं can't declare a static method in an interface) आप यह कर सकते हैं:
var e = Length.Convert<Length.mm, Length.m>(c);
var f = Length.Convert<Length.mm, Mass.kg>(d); <-- but not this
जाहिर है, एफ # इकाइयों के माप की तुलना में इसमें एक अंतर छेद है (मैं आपको इसे काम करने दूँगा)।
ओह, सवाल यह है: आप इसके बारे में क्या सोचते हैं? क्या इसका उपयोग करने लायक है? क्या किसी और ने पहले ही बेहतर किया है? इस विषय क्षेत्र में रुचि रखने वाले लोगों के लिए
अद्यतन, here एक ही माप की विभिन्न इकाइयों के लिए अलग वर्ग का उपयोग करते हुए एक समाधान की एक अलग तरह की चर्चा कर
Frink कैलकुलेटर और Frink प्रोग्रामिंग भाषा पर एक नजर डालें। –
मुझे आश्चर्य है कि किसी ने कक्षा संपत्ति मूल्यों के गुणों के साथ सी # में इकाइयों से संपर्क किया है। – ja72
फ़्रिंक इस प्रकार की समस्या के लिए बम है। –