C# Keywords Series 5 explicit&implicit&operator

来源:互联网 发布:linux iconv命令 编辑:程序博客网 时间:2024/04/30 03:00


  本篇文章主要讲述C#当中的转换关键字,explicit&implicit&operator。大半月没怎么更新博客,楼主最近回家看爹娘了,回来继续DOTNET之旅。 

  Operator

operator  关键字用于重载内置的运算符,或者是提供类或者结构声明中的类型转换。前面讲过的decimal类型,它的运算操作就用到了重载运算符。

  下面是一个简单例子:Person 类,重载 + 和 - 的运算符,同时提供将Person 类型隐式转换为SuperMan类

    class Person    {        // overload operator +        public static Person operator +(Person a, Person b)        {            return new Person((a.Age + b.Age) / 2);        }        // user-defined conversion from Person to SuperMan        public static implicit operator SuperMan(Person p)        {            return new SuperMan();        }  public Person(float temp)        {            age = temp;        }        // Define a Dog class will used next. Declare in below         // Define explicit Person-to-Dog conversion operator    public static explicit operator Dog(Person p)        {            return new Dog(p.age / 10);        }        public float Age        {            get { return age; }        }        private float age;    }      class SuperMan    {        public SuperMan()        {            Console.WriteLine("Eat salty prunes to be Super Man.");        }    }    class Program    {        static void Main(string[] args)        {            Person issac = new Person(23.0f);            Person yang = new Person(32.0f);            Console.WriteLine("issac is {0} years old,yang is {1} years old, the average age is {2}",issac.Age,yang.Age,(issac+yang).Age);            SuperMan issacSuper = issac;}    }    // Output :    // issac is 23 years old,yang is 32 years old, the average age is 27.5    //  Eat salty prunes to be Super Man.

  可以看到当Person 类+Person 类时会生成一种新的Person类,并且他的Age是他们之平均数,也可以注意到,Person 变成SuperMan时存在一个隐性转换。在我看来,这些可以认为都是一种特殊的重载,还是多态的效果。

  explicit

  explicit用于声明时必须使用强制转换的类型运算符,依然用上面的Person类,再添加下面的代码

    class Dog    {        public Dog(float temp)        {            age = temp;          }        // Define conversion Dog to Person        public static explicit operator Person(Dog d)        {            return new Person(10*d.age);        }        public float Age        {            get { return age; }        }        private float age;    }   class Program    {        static void Main(string[] args)        {            Dog bruto = new Dog(10.0f);            Console.Write("As a dog,{0} years old",bruto.Age);            Person jim = (Person)bruto;            Console.WriteLine(" equals to {0} years old as humans. ",jim.Age);        }    }// Output :// As a dog,10 years old equals to 100 years old as humans.

  可以看到Person 到 Dog,或者Dog到Person都需要加强制转换,这是显式转换。

  implicit

  implicit用于类型转换的隐式声明,容易造成数据丢失,在确保不丢失数据时可以用,多用于不必要的转换。

  可以看到前面的代码Person 到 SuperMan 的转换就是隐式转换

 

 SuperMan issacSuper = issac;


  转换关键字就这几个,简单的介绍为止。有何问题,欢迎纠正。

原创粉丝点击