首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

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

2012-08-22 
为什么这里接口类型不能用as 和isunit Unit3interfaceusesWindows, Messages, SysUtils, Variants, Class

为什么这里接口类型不能用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;

热点排行