C# Implicit/Explicit Type Conversion

2019-02-21 19: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:

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.

3条回答
干净又极端
2楼-- · 2019-02-21 20:29
class Number
{  
    public static implicit operator int(Number n)
    {
       return n.Value;
    }
}
查看更多
再贱就再见
3楼-- · 2019-02-21 20:31

Try something like this

    public static implicit operator int(Number num)
    {
        return num.Value;
    }
查看更多
乱世女痞
4楼-- · 2019-02-21 20:39

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.

查看更多
登录 后发表回答