混合应用接口和对象模型的意外

按照Eric Harmon 的说法,如下所示

  IFormattedNumber = interface
    ['{86EF89E2-347C-480F-9A6C-1E57F134E58E}']
    function FormatttedString: string;
    procedure SetValue(AValue: Integer);
  end;


  TFormattedInteger = class(TObject, IFormattedNumber)
  private
    FRefCount: Integer;
    FValue: Integer;
  public
    constructor Create(aValue: Integer);
    function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
    function FormatttedString: string;
    procedure SetValue(AValue: Integer);
  end;

  procedure DoSomethingWithInterface(Intf: IFormattedNumber);

implementation

procedure DoSomethingWithInterface(Intf: IFormattedNumber);
begin
  ShowMessage(Intf.FormatttedString);
end;

procedure CreateAndUseObject;
var
  MyInteger: TFormattedInteger;
begin
  MyInteger := TFormattedInteger.Create(12);
  DoSomethingWithInterface(MyInteger as IFormattedNumber);
  MyInteger.SetValue(10);
end;

{ TFormattedInteger }

constructor TFormattedInteger.Create(aValue: Integer);
begin
  inherited Create;
  FValue := aValue;
end;

function TFormattedInteger.FormatttedString: string;
begin
  Result := 'The Value is ' + IntToStr(FValue)
end;

function TFormattedInteger._AddRef: Integer;
begin
  Inc(FRefCount);
  Result := FRefCount;
end;

function TFormattedInteger._Release: Integer;
begin
  Dec(FRefCount);
  Result := FRefCount;
  if FRefCount = 0 then
    Destroy;
end;

function TFormattedInteger.QueryInterface(const IID: TGUID;
  out Obj): HRESULT;
const
  E_NOINTERFACE = $80004002;
begin
  if GetInterface(IID, Obj) then
    Result := 0
  else
    Result := E_NOINTERFACE;
end;

procedure TFormattedInteger.SetValue(AValue: Integer);
begin
  FValue := AValue;
end;

结果是编译也通不过:
[Error] Unit1.pas(52): Operator not applicable to this operand type
这句有问题了:
DoSomethingWithInterface(MyInteger as IFormattedNumber);

当然这样是没有问题的:DoSomethingWithInterface(MyInteger as IFormattedNumber);

真奇怪,本来是来验证as 对 引用计数的影响的,结果进行不下去了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值