简体   繁体   中英

C# Implicit/Explicit Type Conversion

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:

public class Number
{
    public int Value {get; set;}
    public string Name {get; set;}
}

public static void Print(int print)
{
    Console.WriteLine(print);
}

public static string Test()
{
    Number num = new Number (9, "Nine");
    Print(num); //num "overloads" by passing its integer Value to Print.
}

// Result
// 9

How do I make the Test() function work as I have coded it? Is this even possible? I think this can be done with the explicit/implicit operator but I can't figure it out.

Try something like this

    public static implicit operator int(Number num)
    {
        return num.Value;
    }
class Number
{  
    public static implicit operator int(Number n)
    {
       return n.Value;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM