将对象转为接口( object as interface )怎么会出错?《DELPHI COM深入编程》中的一个例子。(50分)

Y

youou

Unregistered / Unconfirmed
GUEST, unregistred user!
var
MyNumber:IFormattedNumber;
MyInteger:TFormattedInteger;
MyObject:TObject;
begin
MyObject:=TFormattedInteger.Create(9);
if MyObject.GetInterface(IFormattedNumber,MyNumber) then
ShowMessage(MyNumber.FormattedString);

MyObject:=TFormattedInteger.Create(8);

MyNumber:=MyObject as IFormattedNumber; //编译不过哦。。。
出现(Operator not applicable to this operand type)

ShowMessage(MyNumber.FormattedString);
end;
=============================================
IFormattedNumber=interface
['{80517651-65E4-43B0-8628-CF9AB2FA1527}']
function FormattedString:string;
end;

TFormattedInteger=class(TObject,IFormattedNumber)
private
FRefCount:integer;
FValue:Integer;
protected

public
constructor Create(AValue:Integer);

//IUnknown 接口
function QueryInterface(const IID:TGUID;out Obj):HResult;stdcall;
function _AddRef:Integer;stdcall;
function _Release:Integer;stdcall;

//IFormattedNumber接口

function FormattedString:string;
procedure SetValue(Value: integer);
end;

----------------
《DELPHI COM深入编程》中的一个例子。
用GETINTERFACE的方法可以实现。。。


 
1。 MyObject:=TFormattedInteger.Create(9);
if MyObject.GetInterface(IFormattedNumber,MyNumber) then
ShowMessage(MyNumber.FormattedString);

2。MyObject:=TFormattedInteger.Create(8);
MyNumber:=MyObject as IFormattedNumber;
把MyObject换成MyInteger试试 ;
我想如果不换
第1句不会有错!因为根本找不到INTERFACE;
第2句转换就会出错了!
 
我试了。。
不行的!

还有人懂吗?
 
试试
function FormattedString:string;stdcall;
 
还是不行啊~~
 
告诉我constructor Create(AValue:Integer);里面的代码我就可以帮你解决
 
constructor TFormattedInteger.Create(AValue: Integer);
begin
inherited Create;
FValue:=AValue;
end;
 
把代码贴全算了!
 
绝对错误,as操作符相当于调用了QueryInterface,此方法在tobject类中
根本没有提供,可见不能这样使用,as的使用指限于接口类型interface,一个证明是
MyNumber(接口类型)就有QueryInterface方法。得到接口指针可以使用CoCreateInstance
 
首先应该颠倒一下定义的顺序,先定义接口!
 
to delphi浪客:
就是说AS操作根本不支持从 “对象 as 接口“的操作,是吗?


to donkey:
我只是贴出来的顺序反了罢了。。。
 
对啊,接口之间可以通过as来切换的,比如你的实现类实现两个接口
TFormattedInteger=class(TObject,IFormattedNumber,IOther)
应用时
var
MyNumber:IFormattedNumber;
MyOther:IOther;
MyObject:TObject;
begin
MyObject:=TFormattedInteger.Create(9);
MyObject.GetInterface(IOther,MyOther);//得到iother接口
MyObject.GetInterface(IFormattedNumber,MyNumber)//得到IFormattedNumber接口
MyOther= MyNumber as IOther;//得到iother接口
MyNumber = MyOtheras IFormattedNumber;//得到IFormattedNumber接口


 
《DELPHI COM深入编程》的第14页中有误!
谢谢大家!
特别是 感谢delphi浪客!
不好意思,分不多~
 

Similar threads

B
回复
18
查看
143
wjiachun
W
顶部