C# explicit与implicit

1、它们解决什么问题?

  考虑下面的需求,Person类有个字段age。我想使用Person p = (Person) 18 来创建一个age为18的Person对象,怎么办?

  更进一步,我想使用Person p = 18 来创建一个age为18的Person对象,怎么办?

2、使用explicit(显式)和implicit(隐式)

 1    class Person
 2     {
 3         private int age;
 4         public int Age
 5         {
 6             get { return age; }
 7             set { age = value; }
 8         }
 9 
10         public static explicit operator Person(int age)
11         {
12             return new Person() { age = age, };
13         }
14 
15         //public static implicit operator Person(int age)
16         //{
17         //    return new Person() { age = age, };
18         //}
19     }
20 
21     class Program
22     {
23         static void Main(string[] args)
24         {
25             Person p = (Person)18; // 调用explicit
26             //Person p = 18; // 调用implicit
27         }
28     }

注意:二者不同同时提供,否则编译错误。这种语法其实是借鉴了C++的方式,并进行了扩展。一般情况下,不要使用这种类型转换,因为不直观。

原文地址:https://www.cnblogs.com/nzbbody/p/3519688.html