Units of measure in C# - almost

后端 未结 12 1267
再見小時候
再見小時候 2020-11-27 10:29

Inspired by Units of Measure in F#, and despite asserting (here) that you couldn\'t do it in C#, I had an idea the other day which I\'ve been playing around with.

         


        
12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 10:51

    I really liked reading through this stack overflow question and its answers.

    I have a pet project that I've tinkered with over the years, and have recently started re-writing it and have released it to the open source at https://github.com/MafuJosh/NGenericDimensions

    It happens to be somewhat similar to many of the ideas expressed in the question and answers of this page.

    It basically is about creating generic dimensions, with the unit of measure and the native datatype as the generic type placeholders.

    For example:

    Dim myLength1 as New Length(of Miles, Int16)(123)
    

    With also some optional use of Extension Methods like:

    Dim myLength2 = 123.miles
    

    And

    Dim myLength3 = myLength1 + myLength2
    Dim myArea1 = myLength1 * myLength2
    

    This would not compile:

    Dim myValue = 123.miles + 234.kilograms
    

    New units can be extended in your own libraries.

    These datatypes are structures that contain only 1 internal member variable, making them lightweight.

    Basically, the operator overloads are restricted to the "dimension" structures, so that every unit of measure doesn't need operator overloads.

    Of course, a big downside is the longer declaration of the generics syntax that requires 3 datatypes. So if that is a problem for you, then this isn't your library.

    The main purpose was to be able to decorate an interface with units in a compile-time checking fashion.

    There is a lot that needs to be done to the library, but I wanted to post it in case it was the kind of thing someone was looking for.

提交回复
热议问题