复习原型模式引发的base疑惑

懵逼树上懵逼果,懵逼果下你和我,写下来做备注,估计随着知识的把握会更清晰的知道这一部分。

using System;

namespace ConsoleApp1
{
    abstract class prototype
    {
        private int id;

        public prototype(int id)
        {
            this.id = id;
        }
        public int ID
        {
            get { return id; }
        }

        public abstract prototype Clone();
    }

    class ConcretePrototype1 : prototype
    {
        public int id = 10;

        public ConcretePrototype1(int id) : base(id)
        {
            Console.WriteLine("构造函数, 输出的id,{0}", this.ID);
        }

        public override prototype Clone()
        {
            return (prototype)this.MemberwiseClone();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ConcretePrototype1 p1 = new ConcretePrototype1(123);

            p1.id = 100;    //ConcretePrototype1 中的id 设想下一步利p1属性ID输出的id应该是100
            Console.WriteLine("利用ID属性查看输出的p1.id是否发生改变{0}",p1.ID);

            Console.WriteLine("直接修p1中的公共字段id {0}", p1.id);

        }
    }

}

用c#编写的这段代码输出结果是

构造函数, 输出的id 123

利用ID属性查看输出的p1.id是否发生改变123         //可以看到并没有发生变化 还是父类中private id的值 

直接修p1中的公共字段id 100                                     //可以看到直接修改子类中的id之后 输出的id变化为100

即子类通过继承得到ID属性默认对应的是父类的私有id。

更深入的思考待续 欢迎大神指点。


 

猜你喜欢

转载自blog.csdn.net/qq_28595007/article/details/84757381
今日推荐