1. 程式人生 > >神奇的C#內部類作用解讀

神奇的C#內部類作用解讀

C#內部類,一般是宣告為Private,如果宣告public意義不大,下面給出Demo

public class LearnInnerClass
    {
        private bool status;
        private DateTime time;
        public string Say(DateTime _time)
        {
            time = _time;
            Bed bed = new Bed(this);
           
            if(time.Hour>20)
            {
                status = true;
            }
            else
            {
                status = false;
            }
            return bed.GetForSleep();
        }
        private class Bed //內部類的技巧就在這裡private
        {
            private LearnInnerClass outer;
            public Bed(LearnInnerClass inner)//這裡構造
            {
                outer = inner;
            }
            public string GetForSleep()
            {
                if(outer.status)//可以訪問private 值域,呵呵
                {
                    return "床在的你!";
                }
                else
                {
                    return "床在等太陽晒!";
                }
            }
        }
    }