用户定义的类型转换

date
Dec 9, 2021
slug
10032
status
Published
tags
C#
summary
type
Post
首先
using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        { 
            LimitedInt li = 500; //用int 500初始化,调用构造函数LimitedInt(int x),返回LimitedInt类的实例li
            int value = li; //把li类隐式转换为int,即调用int转换函数返回li.TheValue
            Console.WriteLine($"li: {li.TheValue}, value: {value}");
        }
    }
    class LimitedInt
    {
        const int MaxValue = 100;
        const int MinValue = 0;

        public static implicit operator int(LimitedInt li)
        {
            return li.TheValue;
        }
        public static implicit operator LimitedInt(int x) //相当于构造函数,用int初始化
        {
            LimitedInt li = new()
            {
                TheValue = x
            };
            return li;
        }

        private int mTheValue = 0;
        public int TheValue
        {
            get { return mTheValue; }
            set
            {
                if (value < MinValue)
                    mTheValue = 0;
                else
                    mTheValue = value > MaxValue ? MaxValue : value;
            }
        }
    }
}

© Wen Bo 2021 - 2022