神奇的C#内部类作用解读

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuqinfeng/article/details/42179383

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 "床在等太阳晒!";
                }
            }
        }
    }


阅读更多
换一批

没有更多推荐了,返回首页