我正在將Delphi代碼轉換爲C#。C#中沒有「屬性類型」的屬性
我有一個複雜的班級結構,其中一個班級是主要的'幹線'其所有的孩子。
在德爾福我可以定義私有/受保護的字段與一個類型和該屬性相同的類型,而不是寫在兒童類的類型了。
這裏是一個位(和功能)例如:
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#私有/受保護屬性的行爲完全一樣? –
真的,我必須恢復我想要做的事情:我擁有在祖先類中聲明的所有可能的屬性,並且我想只在該子類上「發佈」一組該屬性。不重新聲明整個財產......既不是類型也不是訪問者。 – ferpega