implicit(C# 参考)implicit (C# Reference)

implicit 关键字用于声明隐式的用户定义类型转换运算符。The implicit keyword is used to declare an implicit user-defined type conversion operator. 如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.


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);

隐式转换可以通过消除不必要的强制转换来提高源代码的可读性。By eliminating unnecessary casts, implicit conversions can improve source code readability. 但是,因为隐式转换不需要程序员将一种类型显式强制转换为另一种类型,所以使用隐式转换时必须格外小心,以免出现意外结果。However, because implicit conversions do not require programmers to explicitly cast from one type to the other, care must be taken to prevent unexpected results. 一般情况下,隐式转换运算符应当从不引发异常并且从不丢失信息,以便可以在程序员不知晓的情况下安全使用它们。In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. 如果转换运算符不能满足那些条件,则应将其标记为 explicitIf a conversion operator cannot meet those criteria, it should be marked explicit. 有关详细信息,请参阅使用转换运算符For more information, see Using Conversion Operators.

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also

C# 参考C# Reference
C# 编程指南C# Programming Guide
C# 关键字C# Keywords
运算符(C# 参考)operator (C# Reference)
如何:在结构之间实现用户定义的转换How to: Implement User-Defined Conversions Between Structs