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
'IT박스' 카테고리의 다른 글
LLVM과 Java 바이트 코드의 차이점은 무엇입니까? (0) | 2020.11.15 |
---|---|
브랜치가 생성 된 트렁크에서 개정 찾기 (0) | 2020.11.15 |
모든 것이 "최신"상태 인 경우에도 git이 수신 후 후크를 실행하도록합니다. (0) | 2020.11.15 |
Java 8로 무한 스트림을 만드는 방법 (0) | 2020.11.15 |
RC.1에서는 바인딩 구문을 사용하여 일부 스타일을 추가 할 수 없습니다. (0) | 2020.11.15 |