读书人

为啥这里接口类型不能用as 和is

发布时间: 2012-08-22 09:50:34 作者: rapoo

为什么这里接口类型不能用as 和is
unit Unit3;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
IHuman=interface
function sayhello:string;
property tong:string read sayhello;
end;

TMan=class(TInterfacedObject,IHuman)
function sayhello:string;
property tong:string read sayhello;
end;

TForm3 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form3: TForm3;

implementation

{$R *.dfm}
var Aman:Tman;G:IHuman;
function TMan.sayhello:String;
begin
result:='HelloWorld';
end;
procedure TForm3.Button1Click(Sender: TObject);
begin
AMan:=TMan.Create;
G:=AMan; //这里如果改成if AMan is IHuman then G:=AMan as IHuman;就出错了 E2015 Operatot not applicable to this operand type
showmessage(G.tong);
end;

end.


[解决办法]
1. is操作符是用来判断对象是不是属于某个类,貌似不能用来判断接口。
2. 要在操作接口时使用as操作符,必须让接口有一个GUID(即在IHuman=interface的下一行按Ctrl+Shift+G)。

所以:
procedure TForm3.Button1Click(Sender: TObject);
begin
AMan:=TMan.Create;
if Supports(Aman, ihuman, G) then
showmessage(G.tong);
end;

读书人网 >.NET

热点推荐