码迷,mamicode.com
首页 > 其他好文 > 详细

自定义转换

时间:2015-09-09 13:00:50      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 自定义转换
{
    class LimitedInt
    {
        const int MaxValue = 100;
        const int MinValue = 0;
        private int _TheValue = 0;
        public int TheValue
        {
            get { return _TheValue; }
            set
            {
                if (value < MinValue)
                    _TheValue = 0;
                else
                    _TheValue = value > MaxValue ? MaxValue : value;
            }
        }
        public static implicit operator int(LimitedInt li)
        {
            return li.TheValue;
        }
        public static implicit operator LimitedInt(int x)
        {
            LimitedInt li = new LimitedInt();
            li.TheValue = x;
            return li;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            LimitedInt li = 5;//将5转换为limitedInt
            int Five = li;//将LimitedInt转换为int
            Console.WriteLine("li:{0},Five:{1}",li.TheValue,Five);
            Console.ReadKey();
        }
    }
}

自定义转换

标签:

原文地址:http://www.cnblogs.com/sulong/p/4794022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!