情境:
常使用阿拉伯数字1234567890
但想要有一天在写code时
输入int i = 1234567890
自动帮你转成一二三四五六七八九零
这时候可以使用[explicit,implicict] + operator 转换关键字
来实作功能
举例:
void Main(){int_zh_tw obj_test = 1234567890;Console.WriteLine(obj_test.Value);}class int_zh_tw{public string Value { get; set; }public static implicit operator int_zh_tw(int inValue){var str_int = inValue.ToString().Replace("1","一").Replace("2","二").Replace("3","三").Replace("4","四").Replace("5","五").Replace("6","六").Replace("7","七").Replace("8","八").Replace("9","九").Replace("0","零");return new int_zh_tw() { Value = str_int };}}
原理:
static operator 类别名称
的建构式(图1)通过把传进来的变数,依序以对应繁体中文取代阿拉伯数字(图2)并包装返回同类别名称的物件(图3)想更进一步了解,可以带MSDN了解
Conversion Keywords (C# Reference)