【问题标题】:C# Implicit/Explicit Type ConversionC# 隐式/显式类型转换
【发布时间】:2011-07-01 00:54:54
【问题描述】:

我有一个简单的场景,可能会也可能不会。我有一个包含整数的类,为此我将使其尽可能简单:

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

如何使Test() 函数按照我的编码工作?这甚至可能吗?我认为这可以通过显式/隐式运算符来完成,但我无法弄清楚。

【问题讨论】:

  • 您可以使用implicit 运算符,但是为什么可以将您的类隐式转换为整数如此重要?只是通过num.Value 似乎是一个更好的解决方案。
  • 我明白了。我的语法完全错误。我这样做是因为这个类意味着一个值;我认为只是添加返回 .Value 的隐式部分就很清楚了。
  • 我的相关问题,你可能会感兴趣:Are implicity/explicit conversion methods inherited in C#?

标签: c# .net type-conversion implicit-conversion


【解决方案1】:

隐式类型转换:隐式类型转换发生在较小到较大的整数类型之间,反之亦然,或者在派生类和基类之间。 C# 以类型安全的方式进行转换,不会发生数据丢失。 例如,

int a = 10;
long b = a;
float f = a;

显式类型转换:使用内置 C# 函数完成的显式类型转换。显式类型转换时数据可能会丢失,这意味着如果我们将 double 转换为 int,那么精度可能会丢失。显式类型转换需要强制转换。要进行转换,需要在要转换的值或变量前面指定要转换的类型。

例如,

double d = 10.20;
int a = (int)d;
//Output: 10

详细了解请关注C# Basics - C# Type Conversion

【讨论】:

  • “没有发生数据丢失”并不是很准确,float (.NET Single) 无法准确表示 int 中的所有可能值。
【解决方案2】:
class Number
{  
    public static implicit operator int(Number n)
    {
       return n.Value;
    }
}

【讨论】:

  • 既然已经提供了答案,为什么还要发布您自己的答案?相反,你应该投票赞成那个。
  • 因为我在没有其他答案的情况下回答了它。我一分钟就到了。
【解决方案3】:

试试这样的

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

【讨论】:

    【解决方案4】:

    隐式转换

    // Implicit conversion. num long can
    // hold any value an int can hold, and more!
    int num = 2147483647;
    long bigNum = num;
    

    显式转换

    class Test
    {
        static void Main()
        {
            double x = 1234.7;
            int a;
            // Cast double to int.
            a = (int)x;
            System.Console.WriteLine(a);
        }
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 2016-06-03
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      相关资源
      最近更新 更多