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
*/
}
}
}