用户定义转换运算符(C# 引用)User-defined conversion operators (C# reference)

用户定义类型可以定义从或到另一个类型的自定义隐式或显式转换。A user-defined type can define a custom implicit or explicit conversion from or to another type.

隐式转换无需调用特殊语法,并且可以在各种情况(例如,在赋值和方法调用中)下发生。Implicit conversions don't require special syntax to be invoked and can occur in a variety of situations, for example, in assignments and methods invocations. 预定义的 C# 隐式转换始终成功,且永远不会引发异常或丢失信息。Predefined C# implicit conversions always succeed and never throw an exception or lose information. 用户定义隐式转换也应如此。User-defined implicit conversions should behave in that way as well. 如果自定义转换可能会引发异常或丢失信息,请将其定义为显式转换。If a custom conversion can throw an exception or lose information, define it as an explicit conversion.

isas 运算符不考虑使用用户定义转换。User-defined conversions are not considered by the is and as operators. 强制转换运算符 () 用于调用用户定义显式转换。Use the cast operator () to invoke a user-defined explicit conversion.

operatorimplicitexplicit 关键字分别用于定义隐式转换或显式转换。Use the operator and implicit or explicit keywords to define an implicit or explicit conversion, respectively. 定义转换的类型必须是该转换的源类型或目标类型。The type that defines a conversion must be either a source type or a target type of that conversion. 可用两种类型中的任何一种类型来定义两种用户定义类型之间的转换。A conversion between two user-defined types can be defined in either of the two types.

下面的示例展示如何定义隐式转换和显式转换:The following example demonstrates how to define an implicit and explicit conversion:

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
    }
}

operator 关键字也可用于重载预定义的 C# 运算符。You also use the operator keyword to overload a predefined C# operator. 有关详细信息,请参阅运算符重载For more information, see Operator overloading.

C# 语言规范C# language specification

有关更多信息,请参阅 C# 语言规范的以下部分:For more information, see the following sections of the C# language specification:

请参阅See also