반응형
출처 : https://msdn.microsoft.com/ko-kr/library/ebca9ah3.aspx
출처 : https://msdn.microsoft.com/ko-kr/library/hfw7t1ce.aspx
Base 다음과 같이 파생클래스에서 기본 클래스의 멤버에 액세스하는데 사용 됩니다.
- 다른 메서드로 재정의된 기본 클래스의 메서드를 호출합니다.
- 파생클래스의 인스턴스를 만들때 호출해야하는 기본 클래스 생성자를 지정합니다.
이 예제는 기본 클래스인 person과 파상클래스인 Employee 모두에 getInfo가 있습니다.
base키워드를 사용하면 파생 클래스에서 기본 클래스의 GetInfo메서드를 호출할 수 있습니다.
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee : Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
이 예제에서는 Employee라는 기본 클래스와 SalesEmployee라는 파생 클래스를 정의합니다. SalesEmployee 클래스는 추가 속성 salesbonus를 포함하며 이를 고려하여 CalculatePay 메서드를 재정의합니다
class TestOverride
{
public class Employee
{
public string name;
// Basepay is defined as protected, so that it may be
// accessed only by this class and derrived classes.
protected decimal basepay;
// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}
// Declared virtual so it can be overridden.
public virtual decimal CalculatePay()
{
return basepay;
}
}
// Derive a new class from Employee.
public class SalesEmployee : Employee
{
// New field that will affect the base pay.
private decimal salesbonus;
// The constructor calls the base-class version, and
// initializes the salesbonus field.
public SalesEmployee(string name, decimal basepay,
decimal salesbonus) : base(name, basepay)
{
this.salesbonus = salesbonus;
}
// Override the CalculatePay method
// to take bonus into account.
public override decimal CalculatePay()
{
return basepay + salesbonus;
}
}
static void Main()
{
// Create some new employees.
SalesEmployee employee1 = new SalesEmployee("Alice",
1000, 500);
Employee employee2 = new Employee("Bob", 1200);
Console.WriteLine("Employee4 " + employee1.name +
" earned: " + employee1.CalculatePay());
Console.WriteLine("Employee4 " + employee2.name +
" earned: " + employee2.CalculatePay());
}
}
반응형