implicit(C# 参考)

implicit 关键字用于声明隐式的用户定义类型转换运算符。如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。

class Digit
{
    public Digit(double d) { val = d; }
    public double val;
    // ...other members

    // User-defined conversion from Digit to double
    public static implicit operator double(Digit d)
    {
        return d.val;
    }
    //  User-defined conversion from double to Digit
    public static implicit operator Digit(double d)
    {
        return new Digit(d);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Digit dig = new Digit(7);
        //This call invokes the implicit "double" operator
        double num = dig;
        //This call invokes the implicit "Digit" operator
        Digit dig2 = 12;
        Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
        Console.ReadLine();
    }
}

使用转换运算符。

C# 语言规范

 

有关详细信息,请参阅 C# 语言规范。该语言规范是 C# 语法和用法的权威资料。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
  • 2021-06-07
  • 2021-10-17
  • 2021-07-28
猜你喜欢
  • 2022-03-03
  • 2022-12-23
  • 2022-02-28
  • 2021-05-18
  • 2021-12-20
  • 2021-09-27
  • 2022-01-22
相关资源
相似解决方案