2011-07-03 9 views
3

저는 Delphi 코드를 C#으로 변환하고 있습니다.C에서 '속성 유형'이없는 속성

클래스가 기본 자식 인 'trunk' 인 복잡한 클래스 구조를 사용하고 있습니다.

Delphi에서 동일한 유형의 해당 필드에 대한 유형 및 속성으로 개인/보호 필드를 정의 할 수 있으며 더 이상 하위 클래스에 유형을 쓰지 않습니다. 여기

조금 (및 기능) 예입니다

program Project1; 

{$APPTYPE CONSOLE} 

uses 
    SysUtils; 

type 
    Parent = class 
    strict protected 
    _myFirstField: Int64; 
    public 
    property MyFirstField: Int64 write _myFirstField; 
    end; 

    Child1 = class(Parent) 
    public 
    // Inherits the write/set behaviour.. 
    // And it doesn't need to define the type 'over and over' on all child classes. 
    // 
    // ******* Note MyFirstField here has not type.... ************ 
    property MyFirstField  read _myFirstField; // Adding READ behaviour to the property. 
    end; 

var 
    Child1Instance: Child1; 
begin 
    Child1Instance := Child1.Create; 
    //Child1Instance.MyFirstField := 'An String'; <<-- Compilation error because type 
    Child1Instance.MyFirstField := 11111; 
    WriteLn(IntToStr(Child1Instance.MyFirstField)); 
    ReadLn; 
end. 

당신이 볼 수 있듯이 나는 반복 속성 유형을 정의 할 필요가 없습니다. 나중에 var 유형을 변경해야하는 경우 상위 클래스에서만 변경할 수 있습니다.

C#에서 이와 동일한 문제가 발생하는 방법이 있습니까?

+3

쇼. 일반적인 OOP에 따라 기본 클래스에서 보호 된 속성을 가질 수 있으며 set/get과 함께 하위 클래스에서 사용할 수 있으며 해당 유형 정의가 유지됩니다. –

+0

C# 개인/보호 된 속성 동작이 정확히 동일하지 않습니까? –

+0

정말로 내가하고 싶은 일을 재개해야합니다 : 나는 조상 클래스에서 선언 된 가능한 모든 속성을 갖고 있으며 하위 클래스에 해당 속성 집합 만 "게시"하고 싶습니다. 전체 속성을 다시 선언하지 않고 ... 유형도 접근하지 않습니다. – ferpega

답변

4

아니요, 그렇습니다. 공개 API의 유형은 명시 적이어야합니다. 명시 적으로 지정하지 않은 유일한 시간은 메소드 변수로 제한되는 var입니다.

// base type 
protected string Foo {get;set;} 

// derived type 
new public string Foo { 
    get { return base.Foo; } 
    protected set { base.Foo = value; } 
} 

을하지만 new에서 알 수 있듯이 : -

또한, 당신은 C#에서 서명 (서브 클래스의 공용 게터를 추가)를 변경할 수 없습니다 당신은 그것을 다시 선언해야 이것은이다 관련이없는 재산이며 은 필요하지 않습니다.은 같은 유형입니다.

+0

Marc 고맙습니다. 그런 다음이 동작이 동일 할 때도 "동일한"Foo 속성에 대한 모든 동작을 다시 작성해야합니다. :-( – ferpega

+0

@FerPt 아니오, 내 예제와 같이'base.'에 대한 프록시 만 –

0

지금까지 내가 당신과 같이 할 수있는 이해 : 당신이 C#으로하시기 바랍니다 뭘하려

public class Parent 
{ 
    protected Int64 MyCounter{ get; set; } 
} 

public class Child : Parent 
{ 
    protected string ClassName 
    { 
     get 
     { 
      return "Child"; 
     } 
    } 
} 

public class Runner 
{ 
    static void Main(string[] args) 
    { 
     var c = new Child(); 
     c.Counter++; 

     Console.WriteLIne(c.Counter); 
    } 
}