本文介绍了C#中隐式/显式类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的场景,可能或可能是不可能的。我有一个包含一个整数一类,为这个目的,我会让它尽可能简单:

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

如何让我的测试()函数的工作,因为我有codeD吗?这甚至可能吗?我的认为的这个可以用显式/隐式操作员做了,但我不明白。

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.

推荐答案

尝试像这样

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

这篇关于C#中隐式/显式类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 07:25