在优快云遇到有人提问:
我想做个整数范围在0~100的数据类
例如定义个myInt类
然后让myInt能像int那样定义个数字
例如:
myInt x=54;
如果该数字大于100,则throw抛出错误
关键是不要做成什么
myInt x=new myInt(54);
这样传参数的
要能直接实现的
myInt x=54;
以下是我的代码,希望也能给其它人有点帮助.
namespace c1 { class Program { static void Main(string[] args) { try { myInt myint = new myInt();//你换成101试一下就会抛出异常了. int abc = myint; Console.WriteLine(abc); } catch(Exception e) { Console.WriteLine(e.ToString()); } } } class myInt { private int _int; private myInt(int myint) { this._int = myint; } //利用了重写运算符的思想. public static implicit operator myInt(int myint) { if (myint > 100) throw new Exception("数字大于100了"); return new myInt(myint); } public static implicit operator int(myInt myint) { return myint._int; } } } //public static implicit operator myInt(int myint) 实现了int到myInt的隐式转换. //public static implicit operator int(myInt myint) 实现了myInt到int的隐式转换 //如果要显示转换将关键字implicit换成explicit即可.使用时int abc = (int)myint;