[英]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? 如何使
Test()
函数正常工作,因为我编写了它? 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. 希望这可以帮到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.