C# Implicit/Explicit Type Conversion

后端 未结 4 1921
夕颜
夕颜 2021-01-18 00:36

I have a simple scenario that may or may not be possible. I have a class that contains an integer, for this purpose I\'ll make it as simple as possible:

pub         


        
相关标签:
4条回答
  • 2021-01-18 00:45

    Implicit type conversion: Implicit type conversion takes place between smaller to larger integral types but not vice-versa or between derived class and base class. Conversion takes place in type safe manner by C# and no data loss takes place. For example,

    int a = 10;
    long b = a;
    float f = a;
    

    Explicit type conversion: Explicit type conversion done by using built-in C# functions. Data may be lost while explicit type conversion, means if we convert double to int then precision may be lost. Explicit type conversion require casting. To do a casting, need to specify the type that you are casting to in front of the value or variable to be converted.

    For example,

    double d = 10.20;
    int a = (int)d;
    //Output: 10
    

    To understand in details follow C# Basics - C# Type Conversion

    0 讨论(0)
  • 2021-01-18 00:53

    Implicit conversion

    // Implicit conversion. num long can
    // hold any value an int can hold, and more!
    int num = 2147483647;
    long bigNum = num;
    

    Explicit Conversion

    class Test
    {
        static void Main()
        {
            double x = 1234.7;
            int a;
            // Cast double to int.
            a = (int)x;
            System.Console.WriteLine(a);
        }
    }
    

    Hope this may help you.

    0 讨论(0)
  • 2021-01-18 00:59

    Try something like this

        public static implicit operator int(Number num)
        {
            return num.Value;
        }
    
    0 讨论(0)
  • 2021-01-18 01:03
    class Number
    {  
        public static implicit operator int(Number n)
        {
           return n.Value;
        }
    }
    
    0 讨论(0)
提交回复
热议问题