【发布时间】:2011-07-03 11:47:28
【问题描述】:
我正在将 Delphi 代码转换为 C#。
我有一个复杂的类结构,其中一个类是其所有子类的主要'主干'。
在 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# 中获得同样的行为?
【问题讨论】:
-
请显示您在 C# 中尝试过的内容。按照通常的 OOP,您可以在基类中拥有一个受保护的属性,这将与 set/get 一起在子类中可用,并且当然保持其类型定义。
-
C#私有/受保护的属性行为不就是一模一样吗?
-
真的,我必须恢复我想做的事情:我在祖先类中声明了所有可能的属性,我只想在子类上“发布”一组该属性。无需重新声明整个属性...既不是类型也不是访问者。
-
不,C# 中没有模式可以提高派生类中成员的可见性。您需要像 Marc Gravell 的回答那样创建一个全新的属性。
标签: c# delphi c#-4.0 types accessor