C#中隐式/显式类型转换

编程入门 行业动态 更新时间:2024-10-13 14:23:01
本文介绍了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#中隐式/显式类型转换

本文发布于:2023-07-14 10:17:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!