代码改变世界

C#拾遗系列(2):属性

2008-06-11 14:54  敏捷的水  阅读(424)  评论(0编辑  收藏  举报

 

1. 这里主要演示属性的继承和覆盖

2. 把属性理解为方法,实际上编译器就是把属性生成方法

示例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace NetTest

{

 

   public class TestPerpoerty

    {

 

        class DerivedClass : BaseClass

       {

           private string name = "Name-DerivedClass";

           private string id = "ID-DerivedClass";

 

           new public string Name

           {

               get

               {

                   return name;

               }

 

               // Using "protected" would make the set accessor not accessible.

               set

               {

                   name = value;

               }

           }

 

           // Using private on the following property hides it in the Main Class.

           // Any assignment to the property will use Id in BaseClass.

           new private string Id

           {

               get

               {

                   return id;

               }

               set

               {

                   id = value;

               }

           }

       }

 

 

        class BaseClass

        {

            private string name = "Name-BaseClass";

            private string id = "ID-BaseClass";

 

            public string Name

            {

                get { return name; }

                set { }

            }

 

            public string Id

            {

                get { return id; }

                set { }

            }

        }

 

        public  void Test()

        {

            BaseClass b1 = new BaseClass();

            DerivedClass d1 = new DerivedClass();

 

            b1.Name = "Mary";

            d1.Name = "John";

 

            b1.Id = "Mary123";

            d1.Id = "John123"// The BaseClass.Id property is called.

 

            System.Console.WriteLine("Base: {0}, {1}", b1.Name, b1.Id);

            System.Console.WriteLine("Derived: {0}, {1}", d1.Name, d1.Id);

 

            /*

            输出:

            Name and ID in the base class: Name-BaseClass, ID-BaseClass

            Name and ID in the derived class: John, ID-BaseClass

                        *

            --------------------------------

            注意,如果将 new private string Id 替换为 new public string Id,则得到如下输出:

            Name and ID in the base class: Name-BaseClass, ID-BaseClass

 

            Name and ID in the derived class: John, John123

            */

        }

    }

 

}