我想在现有的Delphi类中添加一个方法.我认为基本类框架可以,但需要访问在我的方法中调用我的方法的对象的一些属性.我似乎无法得到任何工作.
旧类TStringGrid
新类OptStringGrid,其中引用了myNewMethod
//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;
Run Code Online (Sandbox Code Playgroud)
德尔福的新手,请原谅我的术语.我知道示例代码不可编译.我正在寻找访问所述属性的技术.
要访问其方法正在执行的对象的成员,可以使用该Self变量.它会在任何方法体内自动声明和分配.实际上,它的使用通常是隐式的 - 对象的任何成员都自动在方法体内.您通常只需要Self在方法中已存在与您要使用的成员同名的其他变量时限定成员访问权限.
实现方法的关键是你需要确保它们实际上是方法.问题中显示的代码未定义myNewMethod为方法.相反,它是一个独立的子程序.只能在对象上调用方法,因此只有方法才能访问它们被调用的对象.
方法声明出现在类声明中.你可能看起来像这样:
type
TOptStringGrid = class(TStringGrid)
public
function myNewMethod(const Name: string): Integer;
end;
Run Code Online (Sandbox Code Playgroud)
方法定义出现在单元的实现部分以及所有其他子例程主体中,就像在对象检查器中双击事件时IDE为您创建的所有事件处理程序实现一样.那些只是普通的方法.
方法实现与其他某种子例程的实现的区别在于方法名称包含它所属的类的名称:
function TOptStringGrid.myNewMethod(const Name: string): Integer;
begin
// ...
end;
Run Code Online (Sandbox Code Playgroud)
观察TOptStringGrid.上面代码中的部分.这就是编译器知道方法体属于该类而不是任何其他命名的方法myNewMethod.
在该方法体中,您可以访问祖先类的所有已发布,公共和受保护的成员TStringGrid,包括该RowCount属性.
| 归档时间: |
|
| 查看次数: |
245 次 |
| 最近记录: |