C语言 百分网手机站

c#转换关键词explicit的使用

时间:2020-10-05 18:04:58 C语言 我要投稿

c#转换关键词explicit的使用

  引导语:C#适合为独立和嵌入式的系统编写程序,从使用复杂操作系统的大型系统到特定应用的小型系统均适用。以下是小编整理的c#转换关键词explicit的使用,欢迎参考阅读!

  explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。例如,在下面的示例中,此运算符将名为 Fahrenheit 的类转换为名为 Celsius 的`类:

  C#

  // Must be defined inside a class called Farenheit:

  public static explicit operator Celsius(Fahrenheit f)

  {

    return new Celsius((5.0f / 9.0f) * (f.degrees - 32));

  }

  可以如下所示调用此转换运算符:

  C#

  Fahrenheit f = new Fahrenheit(100.0f);

  Console.Write("{0} fahrenheit", f.Degrees);

  Celsius c = (Celsius)f;

  转换运算符将源类型转换为目标类型。源类型提供转换运算符。与隐式转换不同,必须通过强制转换的方式来调用显式转换运算符。如果转换操作可能导致异常或丢失信息,则应将其标记为 explicit。这可以防止编译器无提示地调用可能产生无法预见后果的转换操作。

  省略此强制转换将导致编译时错误 编译器错误 CS0266。

  示例

  下面的示例提供 Fahrenheit 和 Celsius 类,它们中的每一个都为另一个提供显式转换运算符。

  C#

  class Celsius

  {

    public Celsius(float temp)

    {

      degrees = temp;

    }

    public static explicit operator Fahrenheit(Celsius c)

    {

      return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);

    }

    public float Degrees

    {

      get { return degrees; }

    }

    private float degrees;

  }

  class Fahrenheit

  {

    public Fahrenheit(float temp)

    {

      degrees = temp;

    }

    // Must be defined inside a class called Farenheit:

    public static explicit operator Celsius(Fahrenheit f)

    {

      return new Celsius((5.0f / 9.0f) * (f.degrees - 32));

    }

    public float Degrees

    {

      get { return degrees; }

    }

    private float degrees;

  }

  class MainClass

  {

    static void Main()

    {

      Fahrenheit f = new Fahrenheit(100.0f);

      Console.Write("{0} fahrenheit", f.Degrees);

      Celsius c = (Celsius)f;

      Console.Write(" = {0} celsius", c.Degrees);

      Fahrenheit f2 = (Fahrenheit)c;

      Console.WriteLine(" = {0} fahrenheit", f2.Degrees);

    }

  }

  /*

  Output:

  100 fahrenheit = 37.77778 celsius = 100 fahrenheit

  */

  下面的示例定义一个结构 Digit,该结构表示单个十进制数字。定义了一个运算符,用于将 byte 转换为 Digit,但因为并非所有字节都可以转换为 Digit,所以该转换是显式的。

  C#

  struct Digit

  {

    byte value;

    public Digit(byte value)

    {

      if (value > 9)

      {

        throw new ArgumentException();

      }

      this.value = value;

    }

    // Define explicit byte-to-Digit conversion operator:

    public static explicit operator Digit(byte b)

    {

      Digit d = new Digit(b);

      Console.WriteLine("conversion occurred");

      return d;

    }

  }

  class ExplicitTest

  {

    static void Main()

    {

      try

      {

        byte b = 3;

        Digit d = (Digit)b; // explicit conversion

      }

      catch (Exception e)

      {

        Console.WriteLine("{0} Exception caught.", e);

      }

    }

  }

  /*

  Output:

  conversion occurred

  */

【c#转换关键词explicit的使用】相关文章:

1.c#访问关键词base的使用

2.c#中预处理指令#if的使用

3.c#中访问关键词 this 的常用用途

4.c#查询关键字之into的使用

5.c#中预处理指令#line的使用

6.c#运算符关键字is的使用

7.c#查询关键字之group子句的使用

8.C# 术语大全