- using System;
- using System.Collections.Generic;
- using System.Text;
- //用户自定义转换
- //所有的用户自定义转换都是静态的,要使用static关键字
- //用户自定义转换分显示和隐示,它们用implicit(隐式转换)或 explicit(显示转换)关键字声明。
- //static 访问修辞符 转换修辞符 operator 转换类型(参数)
- namespace CountStrDemo
- {
- class 自定义类型转换
- {
- //public static void Main(string[] args)
- //{
- // MyCaseDemo obj = new MyCaseDemo( 5 , 8 );
- // //隐式转换
- // float f = obj;
- // Console.WriteLine( f.ToString() );
- // //显式转换
- // int i = (int)obj;
- // Console.WriteLine( i.ToString() );
- // Console.Read();
- //}
- class MyCaseDemo
- {
- public int x;
- public int y;
- public MyCaseDemo(int x, int y)
- {
- this.x = x;
- this.y = y;
- }
- // 与运算重载差区别, operator后跟着的是要转成的类型,不是符号.同时也是本方法的返回类型
- //还及是必须用implicit(隐式转换)或 explicit(显示转换)关键字声明。
- public static implicit operator float(MyCaseDemo obj)
- {
- return obj.y * obj.x;
- }
- public static explicit operator int ( MyCaseDemo obj )
- {
- return obj.y + obj.x;
- }
- }
- }
- }
-
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace CountStrDemo
- {
- class 类与类的自定义转换
- {
- public static void Main(string[] args)
- {
- C c = new C();
- D d = c;
- Console.WriteLine( d.name );
- Console.Read();
- }
- }
- class B
- {
- }
- class C : B
- {
- public string name = "c name";
- public static implicit operator D(C c)
- {
- D d = new D() ;
- d.name = c.name + "让人给搞了";
- return d;
- }
- }
- class D : B
- {
- public string name = "d name";
- }
- }
- // 类与类之前的转换,不能转换两个直接或者简介继承的关系的类,
- //在上例中 C->B D-B都是不对的,唯一的关系只有C->D或者D-C,但是,不可以在CD两类中都定义转换,否则会让编译器搞不清
C#中的自定义类型转换
最新推荐文章于 2024-04-19 14:00:13 发布