属性

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AttributeDemo
{
    
/// <summary>
    
/// 属性的继承和覆盖
    
/// 编译器实际上就是把属性生成方法,所以可以把属性理解为方法
    
/// </summary>
    class Test
    {
        
static void Main(string[] args)
        {
            BaseClass b1 
= new BaseClass();
            DerivedClass b2 
= new DerivedClass();

            b1.Name 
= "Mary";
            b2.Name 
= "John";

            b1.Id 
= "Mary123";
            b2.Id 
= "John123";

            Console.WriteLine(
"Base:{0},{1}", b1.Name, b1.Id);
            Console.WriteLine(
"Derived:{0},{1}", b2.Name, b2.Id);
            Console.ReadKey();
            
//结果是: Base: Name-BaseClass,ID-BaseClass
            
//        Derived: John,ID-BaseClass
            
//如果将new private string id 改为new public string Id
            
//结果是: Derived: John,John123
        }
    }
    
class DerivedClass : BaseClass
    {
        
private string name = "Name-DerivedClass";
        
private string id = "ID-DerivedClass";

        
new public string Name
        {
            
get { return name; }
            
set { name = value; }
        }
        
//注意private
        new private string Id
        {
            
get { return id; }
            
set { id = value; }
        }
    }
    
public class BaseClass
    {
        
private string name = "Name-BaseClass";

        
public string Name
        {
            
get { return name; }
            
set { }
        }

        
private string id = "ID-BaseClass";

        
public string Id
        {
            
get { return id; }
            
set { }
        }
    }
}

 

 

posted @ 2010-05-25 08:56  smodi  阅读(202)  评论(0编辑  收藏  举报