C# 自定义类型转换

1、显式转换和隐式转换:

int a=123;
long b=a;        // 从int到long的隐式转换
int c=(int) b;   // 从long到int是显式转换
---------------------------------------------------------

class Base{}
class Derived:Base{}

class Program
{
     static void Main(string[] args)
     {
          Base myBaseType;
          // 派生类向基类的隐式强制类型转换
          myBaseType = new Derived ();
          // 在派生类型中存储基类引用必须显式强制类型转换
          Derived myDerivedType= (Derived)myBaseType ;
     }
}

2、创建自定义转换例程

public static explicit operator  xx类 (yy类 y)
{
      xx类 x= new xx类();
      y.porp =x.porp;
      return x;
}

1)使用operator关键字

2)operator结合使用explicit或implicit关键字

3)方法必须定义为静态的

4)传入的参数y是要转换的实例,而操作符类型是转换后的实例

5)explicit显式转换

6)implicit隐式转换

原文地址:https://www.cnblogs.com/senyier/p/6617579.html