Passing nil as a parameter in place of a TComponent

删除回忆录丶 提交于 2019-12-20 05:42:12

问题


I've come across some code that's throwing an exception (EIntfCasterror Cast not supported) when it passes nil to a constructor expecting a TComponent, like so:

obj := SomeClass.Create(nil);

The unit this is in does not contain a form and even TForm requires a TComponent be passed to it when you call its constructor. What should I pass in place of nil if anything exists or is there a way to get it to accept nil.

Thank you.

Also, I don't have the source code which calls the method this is in, or I would just have it pass the form it has access to.

EDIT: Fixed the code example.

EDIT2: Fixed the code example because I had a second brain fart when I first wrote it.

EDIT3: I don't have the code for the constructor either.


回答1:


EIntfCastError has nothing to do with the Owner passed in the constructor. It's because you try to cast an interface to another interface you think it supports when it doesn't in fact support it.

MyNewInterface := MyInterface as IADifferentInterface;

You're never ever required to pass in Owner, even when creating a TForm. The following code is perfectly legal:

var
  MyForm: TForm1;
begin
  MyForm := TForm1.Create(nil);
  try
    MyForm.ShowModal;
  finally
    MyForm.Free;
  end
end;

So is this (although it's pretty dumb - it illustrates the point, though):

implementation

var
  Button: TButton;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Button := TButton.Create(nil);
  Button.Parent := Form1;
  Button.Left := 10;
  Button.Top := 10;
  Button.Caption := 'Button';
  Button.Name := 'MyDumbButton';
  Button.OnClick := TheButtonClick;
end;

procedure TForm1.TheButtonClick(Sender: TObject);
begin
  ShowMessage(TButton(Sender).Name + ' clicked');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Button.Free;
end;


来源:https://stackoverflow.com/questions/5419901/passing-nil-as-a-parameter-in-place-of-a-tcomponent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!