写像int类这样的密封的类

本文介绍如何在C#中创建一个名为myInt的自定义整数类,该类限制数值范围为0~100,并通过重写运算符实现整型与myInt之间的隐式转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 在优快云遇到有人提问:

我想做个整数范围在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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值