Favicon

Virtual modifier

Peponi11/27/20242m

C#
SyntaxKeywordModifier

1. Introduction

virtual 한정자는 파생 클래스에서 재정의를 할 수 있게 해준다. 기본 구현을 할 수 있으며, 파생 클래스에서 재정의할 때 기본 구현을 변경할 수 있다.

재정의 또는 숨김 처리 등을 위해 override, new 한정자를 사용할 수 있으나 static 한정자는 적용할 수 없다.

2. Example

public class CartesianCoordinate
{
    public double X = 0, Y = 0;
 
    public CartesianCoordinate(double x, double y)
    {
        X = x;
        Y = y;
    }
 
    public virtual double GetDiagonal() => Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));
}
 
public class CartesianCoordinate3D : CartesianCoordinate
{
    public double Z = 0;
 
    public CartesianCoordinate3D(double x, double y, double z) : base(x, y) => Z = z;
 
    public override double GetDiagonal() => Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2) + Math.Pow(Z, 2));
}
public class PropertyExample
{
    public virtual string Text { get; set; } = "This is text";
}
 
public class PropertyDerived : PropertyExample
{
    string _text;
 
    public override string Text
    {
        get => _text;
        set
        {
            _text = value;
            Console.WriteLine(value);
        }
    }
}

3. 참조 자료