Can you use Enum for Double variables?

后端 未结 6 479
情话喂你
情话喂你 2021-01-02 07:00

I have created a class for handling Unit Conversion in C#. It is not working as it should only returning strings.

Here is the class:

using System;
us         


        
相关标签:
6条回答
  • 2021-01-02 07:47

    Nope:

    I tried giving this to Visual Studio:

    public enum Test : double
    {
        Hello, World
    }
    

    And it said:

    Type byte, sbyte, short, ushort, int, uint, long, or ulong expected

    0 讨论(0)
  • 2021-01-02 07:49

    You cant use enum with doubles. You can only use it with int and long

    0 讨论(0)
  • 2021-01-02 07:51

    You can convert a double to a long using the BitConverter.DoubleToInt64Bits(double) method before hand and hardcode them into an enum with the backing long type. Then you would have to convert the enum value back to a double.

    It is probably more trouble than it is worth.

    0 讨论(0)
  • 2021-01-02 07:53

    No, The default type for enum is int or long and you could not use fractional numbers with it. You can use a struct or class intead of enum for double

    public struct Units
    {
            public const double Grams = 1;
            public const double KiloGrams = 0.001;
            public const double Milligram = 1000;
            public const double Pounds = 0.00220462;
            public const double Ounces = 0.035274;
            public const double Tonnes = 0.000001;
            // Add Remaining units / values
    }
    

    And use it like

    double d = Units.KiloGrams;
    
    0 讨论(0)
  • 2021-01-02 08:00

    You can't use float/double with enums. You may have to define constants.

    public const double KiloGrams = 0.001;
    
    0 讨论(0)
  • 2021-01-02 08:05

    Sorry, can't be done. Enums are strictly integers/bytes. Really, they are supposed to be their own type.

    You can try:

    enum Units() {
        Grams ,
        KiloGrams ,
        Milligram 
    }
    
    public function GetUnitsFloatValue(Units unit) : float
    {
        switch (unit)
        {
            case Units.Grams :
                return 1;
            case Units.KiloGrams :
                return 0.001;
            case Units.MilliGrams:
                return 1000;           
        }
    
        //unhandled unit?
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题