Program Club

C #에서 속성 선언의 "new"키워드

proclub 2020. 11. 8. 11:29
반응형

C #에서 속성 선언의 "new"키워드


유지 관리 할 .net 프로젝트를 받았습니다. 코드를 살펴보고 속성 선언에서 이것을 발견했습니다.

public new string navUrl
{
  get 
  {
    return ...;
  }
  set
  {
    ...
  }
}

new수정자가 속성에 어떤 역할을하는지 궁금 합니다.


기본 클래스의 navUrl 속성을 숨 깁니다. 새로운 수정 자를 참조하십시오 . MSDN 항목에서 언급했듯이 정규화 된 이름으로 "숨김"속성에 액세스 할 수 있습니다 BaseClass.navUrl.. 둘 중 하나를 남용하면 엄청난 혼란과 광기 (예 : 손상된 코드)가 발생할 수 있습니다.


new 재산을 숨기는 것입니다.

코드에서 다음과 같을 수 있습니다.

class base1
{
    public virtual string navUrl
    {
        get;
        set;
    }
}

class derived : base1
{
    public new string navUrl
    {
        get;
        set;
    }
}

여기 파생 클래스에서 navUrl속성은 기본 클래스 속성을 숨기고 있습니다.


이것도 여기에 문서화되어 있습니다 .

msdn의 코드 조각.

public class BaseClass
{
    public void DoWork() { }
    public int WorkField;
    public int WorkProperty
    {
        get { return 0; }
    }
}

public class DerivedClass : BaseClass
{
    public new void DoWork() { }
    public new int WorkField;
    public new int WorkProperty
    {
        get { return 0; }
    }
}    

DerivedClass B = new DerivedClass();
B.WorkProperty;  // Calls the new property.

BaseClass A = (BaseClass)B;
A.WorkProperty;  // Calls the old property.

Some times referred to as Shadowing or method hiding; The method called depends on the type of the reference at the point the call is made. This might help.


https://msdn.microsoft.com/en-us/library/435f1dw2.aspx

Look at the first example here, it gives a pretty good idea of how the new keyword can be used to mask base class variables

참고URL : https://stackoverflow.com/questions/3649174/new-keyword-in-property-declaration-in-c-sharp

반응형