用户定义的类型可以定义自定义隐式或显式转换,前提是同一两种类型之间不存在标准转换。 隐式转换不需要调用特殊语法,并且可能发生在各种情况下,例如,在赋值和方法调用中。 预定义的 C# 隐式转换始终成功,并且永远不会引发异常。 用户定义的隐式转换也应以这种方式运行。 如果自定义转换可以引发异常或丢失信息,请将其定义为显式转换。
是和作为运算符不考虑用户定义的转换。 使用 强制转换表达式 调用用户定义的显式转换。
operator
使用和implicit
或explicit
关键字分别定义隐式或显式转换。 定义转换的类型必须是源类型或该转换的目标类型。 可以在两种类型之一中定义两种用户定义类型的转换。
以下示例演示如何定义隐式和显式转换:
using System;
public readonly struct Digit
{
private readonly byte digit;
public Digit(byte digit)
{
if (digit > 9)
{
throw new ArgumentOutOfRangeException(nameof(digit), "Digit cannot be greater than nine.");
}
this.digit = digit;
}
public static implicit operator byte(Digit d) => d.digit;
public static explicit operator Digit(byte b) => new Digit(b);
public override string ToString() => $"{digit}";
}
public static class UserDefinedConversions
{
public static void Main()
{
var d = new Digit(7);
byte number = d;
Console.WriteLine(number); // output: 7
Digit digit = (Digit)number;
Console.WriteLine(digit); // output: 7
}
}
从 C# 11 开始,可以定义 已检查的 显式转换运算符。 有关详细信息,请参阅算术运算符一文的用户定义的 checked 运算符部分。
还可以使用 operator
关键字重载预定义的 C# 运算符。 有关详细信息,请参阅 运算符重载。
C# 语言规范
有关更多信息,请参阅 C# 语言规范的以下部分:
另请参阅
- C# 运算符和表达式
- 运算符重载
- 类型测试和强制转换运算符
- 转换和类型转换
- 设计准则 - 转换运算符
- C 中的链接用户定义显式转换#