类的成员,如果没有private、public等显示什么,直接在class下面,没有写访问权限的限定符,这种成员是不是默认的访问权限啊?还是publish的访问权限啊?
----------------------------------------------------------
什么答案都有, 就是都不愿意动手, 让我们来看看答案是什么吧
implementation uses
rtti, typinfo;
{$R *.dfm} type TTest1 = class
MemberOfTTest1: Integer;
end; TTest2 = class(TPersistent)
MemberOfTest2: TObject;
end; {$M+}
TTest3 = class
MemberOfTest3: TObject;
end;
{$M-} TMemberVisibilityHelper = record helper for TMemberVisibility
public
function ToString: string;
end; function TMemberVisibilityHelper.ToString: string;
const
VisibilityStrings: array [TMemberVisibility] of string = ('Private', 'Protected', 'Public', 'Published');
begin
Result := VisibilityStrings[Self];
end; procedure TForm1.ShowMemberOf(const obj: TClass);
var
rttiContext: TRttiContext;
rttiType: TRttiType;
rttiField: TRttiField;
begin
rttiContext := TRttiContext.Create;
rttiType := rttiContext.GetType(obj);
for rttiField in rttiType.GetFields do
begin
mmo1.Lines.Add(Format('FieldName: %s, Visibility: %s', [rttiField.Name, rttiField.Visibility.ToString]));
end;
end; procedure TForm1.btn1Click(Sender: TObject);
begin
ShowMemberOf(TTest1);
ShowMemberOf(TTest2);
ShowMemberOf(TTest3);
end;
最后程序输出的结果是:
FieldName: MemberOfTTest1, Visibility: Public
FieldName: MemberOfTest2, Visibility: Published
FieldName: MemberOfTest3, Visibility: Published
大家应该知道了吧, 如果没有被{$M+} 修饰过的, 默认是public的, 相反则是published的, 而第2个TPersistent类在classes单元中声明的时候就是已经被{$M+}包裹起来的, 单独给出一个答案的人要被打脸了哦, 偷懒啊 :)
-----------------------------------------------------------
其实大家每天都这样调用form1.button1就能调用,而且button1在DFM文件里有各种属性,所以当然是published。
不过C++属性不加修饰,确实是private,也不知道为啥两者有这个区别?都是OO语言,但是指导思想不一样?