如何从Delphi 10.1 Berlin中的班级助手访问私有字段? [英] How to access a private field from a class helper in Delphi 10.1 Berlin?

查看:96
本文介绍了如何从Delphi 10.1 Berlin中的班级助手访问私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Gabriel Corneanu的 jpegex ,是jpeg.TJPEGImage的类帮助器。
阅读,我了解到在西雅图德尔福市以外,您无法访问私有字段就像jpegex一样(在下面的示例中为FData)。像David Heffernan提议的那样,在VMT上闲逛远远超出了我。有没有更简单的方法来完成此操作?

I would like to use Gabriel Corneanu's jpegex, a class helper for jpeg.TJPEGImage. Reading this and this I've learned that beyond Delphi Seattle you cannot access private fields anymore like jpegex does (FData in the example below). Poking around with the VMT like David Heffernan proposed is far beyond me. Is there any easier way to get this done?

   type
  // helper to access TJPEGData fields
  TJPEGDataHelper = class helper for TJPEGData
    function  Data: TCustomMemoryStream; inline;
    procedure SetData(D: TCustomMemoryStream);
    procedure SetSize(W,H: integer);
  end;

// TJPEGDataHelper
function TJPEGDataHelper.Data: TCustomMemoryStream;
begin
  Result := self.FData;
end;


推荐答案

当心!这是一个讨厌的黑客,当被黑客入侵的类的内部字段结构发生更改时,它可能会失败。

Beware! This is a nasty hack and can fail when the internal field structure of the hacked class changes.

type
  TJPEGDataHack = class(TSharedImage)
    FData: TCustomMemoryStream; // must be at the same relative location as in TJPEGData!
  end;

  // TJPEGDataHelper
function TJPEGDataHelper.Data: TCustomMemoryStream;
begin
  Result := TJPEGDataHack(self).FData;
end;

这仅在 hack类的父类与父类相同时起作用原始班级的因此,在这种情况下,TJPEGData继承自TSharedImage, hack类也继承。位置也需要匹配,因此,如果列表中的FData之前有一个字段,则即使不使用该字段,也应在 hack类中包含一个等效字段。

This will only work if the parent class of the "hack" class is the same as the parent class of the original class. So, in this case, TJPEGData inherits from TSharedImage and so does the "hack" class. The positions also need to match up so if there was a field before FData in the list then an equivalent field should sit in the "hack" class, even if it's not used.

有关其工作原理的完整说明,请参见:

A full description of how it works can be found here:

技巧5:访问私有字段

这篇关于如何从Delphi 10.1 Berlin中的班级助手访问私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆