开发者

Properties without 'property type' in C#

I am converting a Delphi code to a C#.

I have a complex classes structure where a class is the main 'trunk' of all its children.

In Delphi I can define the private/protected field with a type and the property for that field with the same type, and not write the type in child classes anymore.

Here is a bit (and functional) example:

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.

As you can see I don't need to define the property type over and over. If I need to c开发者_高级运维hange the var type in the future, I can change only in the parent class.

Is there any way to get this same behaviour in C#?


No, there ist. The types on the public API must be explicit. The only time you aren't explicit is with var, which is limited to method variables.

Further, you can't change the signature in C# (adding a public getter in the subclass) - you would have to re-declare it:

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

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

But as the new suggests: this is an unrelated property and is not required to have the same type.


As far as I understand you can do like this:

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜