【Unity】Unity C#基础(十五)implicit 隐式类型转换、explicit 显式类型转换


implicit 隐式类型转换

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

使用隐式转换操作符之后,在编译时会跳过异常检查,所以隐式转换运算符应当从不引发异常并且从不丢失信息,否则在运行时会出现一些意想不到的问题。

例如当前PaymentDTO和Payment的定义如下

public class Payment
{
    
    
     public decimal Amount {
    
     get; set; }
}


public class PaymentDTO
{
    
    
     public string AmountString {
    
     get; set; }
}

如果需要将Payment隐式转换成PaymentDTO, 仅需声明PaymentDTO的隐式转换运算符

public class PaymentDTO
{
    
    
    public string AmountString {
    
     get; set; }

    public static implicit operator PaymentDTO(Payment payment)
    {
    
    
        return new PaymentDTO
        {
    
    
            AmountString = payment.Amount.ToString("C2")
        };
    }
}

调用时只需要直接赋值就可以

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        PaymentDTO dto = new Payment {
    
     Amount = 1 };

        Console.WriteLine(dto.AmountString);
        Console.Read();
    }
}

Explicit 显式类型转换

Explicit关键字声明必须通过转换来调用的用户定义的类型转换运算符。不同于隐式转换,显式转换运算符必须通过转换的方式来调用,如果缺少了显式的转换,在编译时就会产生错误。

例如现在我们将前面PaymentDTO类中定义的转换操作符从Implicit变为Explicit

public class PaymentDTO
{
    
    
     public string AmountString {
    
     get; set; }

     public static explicit operator PaymentDTO(Payment payment)
     {
    
    
         return new PaymentDTO
         {
    
    
             AmountString = payment.Amount.ToString("C2")
         };
     }
 }

这时候由于Main方法中没有显式转换,所以编译器出错,提示Cannot implicitly convert type ‘ExplicitImplicit.Payment’ to ‘ExplicitImplicit.PaymentDTO’. An explicit conversion exists (are you missing a cast?
在这里插入图片描述
如果想要编译器通过编译, 只需要做一个显示转换即可

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        PaymentDTO dto = (PaymentDTO)new Payment {
    
     Amount = 1 };

        Console.WriteLine(dto.AmountString);
        Console.Read();
    }
}

总结

  • Implicit提高了代码的可读性,但程序员需要自己保证转换不引发异常且不丢失信息。
  • Explicit可阻止编译器静默调用可能产生意外后果的转换操作。
  • 前者更易于使用,后者能向阅读代码的每个人清楚地指示您要转换类型。

本文转载自:C#中的Explicit和Implicit,感谢分享。

更多内容请查看总目录【Unity】Unity学习笔记目录整理

猜你喜欢

转载自blog.csdn.net/xiaoyaoACi/article/details/130055322