问题描述
当将 nil 传递给期望 TComponent 的构造函数时,我遇到了一些引发异常(不支持 EIntfCasterror Cast)的代码,如下所示:
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);
它所在的单元不包含表单,甚至 TForm 也需要在调用其构造函数时将 TComponent 传递给它.如果存在任何东西,或者有办法让它接受 nil,我应该通过什么来代替 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.
谢谢.
另外,我没有调用这个方法的源代码,或者我只会让它传递它可以访问的表单.
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.
修正了代码示例.
修正了代码示例,因为我第一次写它时有第二个脑袋放屁.
Fixed the code example because I had a second brain fart when I first wrote it.
我也没有构造函数的代码.
I don't have the code for the constructor either.
推荐答案
EIntfCastError
与构造函数中传入的Owner无关.这是因为您尝试将一个接口转换为您认为它支持的另一个接口,而实际上它并不支持它.
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;
您永远不会要求传入 Owner,即使在创建 TForm 时也是如此.以下代码完全合法:
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;
这篇关于传递 nil 作为参数代替 TComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!