C# 中的类型转换包括:显式类型转换和隐式类型转换。今天我来介绍如何在 C# 中自定义类型转换。

首先是值类型的自定义类型转换:

    public struct MyStruct
    {        
        // 自定义类型转:整形 显式转换为 MyStruct 型
        static public explicit operator MyStruct(int myNo)
        {
            return new MyStruct(myNo);
        }

    }

然后是引用类型的自定义类型转换:

    public class MyClass
    {
        // 自定义类型转换:MyClass 隐式转换为 string 型
        static public implicit operator string(MyClass mc)
        {
            return mc.ToString();
        }

        public override string ToString()
        {
            return _myNo.ToString();
        }
    }

最后,我们对自定义的类型做以测试:

        public static void Main(string[] args)
        {          
            MyStruct MyNum;
            int i = 100;
            MyNum = (MyStruct)i; // 这里是显式转换
            Console.WriteLine("整形显式转换为MyStruct型---");
            Console.WriteLine(i);

            MyClass MyCls = new MyClass(200);
            string str = MyCls; // 这里是隐式转换
            Console.WriteLine("MyClass型隐式转换为string型---");
            Console.WriteLine(str);                   
	}

应用场景:

比如,在结构类型 System.Nullable<T> 中定义了

	public struct Nullable<T> where T : struct    
	{        
		public static implicit operator T?(T value);        
		public static explicit operator T(T? value);    
	}

那么我们就可以,比如:

int num = 10;
int? newNum = num;  // 这里是 隐式类型转换
int age = (int)newNum;   // 这里是 显示类型转换

谢谢浏览!

相关文章:

  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-23
猜你喜欢
  • 2021-12-08
  • 2022-01-17
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案