IT박스

C #에서 속성을 재정의 할 수 있습니까?

itboxs 2020. 11. 15. 11:03
반응형

C #에서 속성을 재정의 할 수 있습니까? 어떻게?


이 기본 클래스가 있습니다.

abstract class Base
{
  public int x
  {
    get { throw new NotImplementedException(); }
  }
}

그리고 다음 자손 :

class Derived : Base
{
  public int x
  {
    get { //Actual Implementaion }
  }
}

컴파일 할 때 Derived 클래스의 정의 x가 Base의 버전을 숨길 것이라는 경고가 표시 됩니다. 메서드와 같은 C #의 속성을 재정의 할 수 있습니까?


virtual키워드 를 사용해야 합니다

abstract class Base
{
  // use virtual keyword
  public virtual int x
  {
    get { throw new NotImplementedException(); }
  }
}

또는 추상 속성을 정의합니다.

abstract class Base
{
  // use abstract keyword
  public abstract int x { get; }
}

그리고 override아이에있을 때 키워드를 사용 하십시오 :

abstract class Derived : Base
{
  // use override keyword
  public override int x { get { ... } }
}

재정의하지 new않으려면 메서드에 키워드를 사용 하여 부모의 정의를 숨길 수 있습니다 .

abstract class Derived : Base
{
  // use override keyword
  public new int x { get { ... } }
}

기본 속성을 추상화하고 파생 클래스에서 새 키워드를 재정의하거나 사용합니다.

abstract class Base
{
  public abstract int x { get; }
}

class Derived : Base
{
  public override int x
  {
    get { //Actual Implementaion }
  }
}

또는

abstract class Base
{
  public int x { get; }
}

class Derived : Base
{
  public new int x
  {
    get { //Actual Implementaion }
  }
}

아래와 같이 속성 서명을 변경합니다.

기본 클래스

public virtual int x 
{ get { /* throw here*/ } }

파생 클래스

public override int x 
{ get { /*overriden logic*/ } }

Base 클래스에서 구현이 필요하지 않으면 추상 속성을 사용하십시오.

베이스:

public abstract int x { get; }

파생 :

public override int x { ... }

I would suggest you using abstract property rather than trhowing NotImplemented exception in getter, abstact modifier will force all derived classes to implement this property so you'll end up with compile-time safe solution.


abstract class Base 
{ 
  // use abstract keyword 
  public virtual int x 
  { 
    get { throw new NotImplementedException(); } 
  } 
} 

abstract class Base
{

  public virtual int x
  {
    get { throw new NotImplementedException(); }
  }
}

or

abstract class Base
{
  // use abstract keyword
  public abstract int x
  {
    get;
  }
}

In both case you have to write in the derived class

public override int x
  {
    get { your code here... }
  }

difference between the two is that with abstract you force the derived class to implement something, and with virtaul you can provide a default behavior that the deriver can use as is, or change.

참고URL : https://stackoverflow.com/questions/8447832/can-i-override-a-property-in-c-how

반응형