我想在现有的Delphi类中添加一个方法。我认为基本类框架可以,但需要访问在我的方法中调用我的方法的对象的一些属性。我似乎无法工作。
旧类TStringGrid
引用myNewMethod的新类OptStringGrid
//example of new class method
procedure myNewMethod (const Name: string);
begin
//Here is my question location.
// I would like to access properties of the calling object in this case
// testgrid. Like... i:= testgrid.rowcount;
end
// Unit Calling statements
var
testGrid : OptStringGrid;
i: integer;
begin
i := testgrid.myNewMethod(strName);
end;
Delphi的新手,请原谅我的术语。我知道示例代码不可编译。我正在寻找技术来访问所描述的属性。
答案 0 :(得分:7)
要访问正在执行其方法的对象的成员,可以使用Self
变量。它会在任何方法体内自动声明和分配。实际上,它的使用通常是隐式 - 对象的任何成员都自动在方法体内的范围。当方法中已经存在与您希望使用的成员同名的其他变量时,通常只需要使用Self
限定成员访问权限。
实现方法的关键是你需要确保它们实际上是方法。问题中显示的代码未将myNewMethod
定义为方法。相反,它是一个独立的子程序。只能在对象上调用方法,因此只有方法才能访问它们被调用的对象。
方法声明出现在类声明中。你的看起来可能是这样的:
type
TOptStringGrid = class(TStringGrid)
public
function myNewMethod(const Name: string): Integer;
end;
方法 definition 出现在您单元的 implementation 部分,以及所有其他子例程主体,就像IDE为您创建的所有事件处理程序实现一样双击对象检查器中的事件时。这些只是普通的方法。
方法实现与其他某种子例程的实现的区别在于方法名称包含它所属的类的名称:
function TOptStringGrid.myNewMethod(const Name: string): Integer;
begin
// ...
end;
观察上面代码中的TOptStringGrid.
部分。这就是编译器知道方法体属于该类而不是名为myNewMethod
的任何其他内容的方式。
在该方法体中,您可以访问祖先类TStringGrid
的所有已发布,公开和受保护的成员,包括RowCount
属性。