英文:
Helper Record not validated on compile
问题
使用Delphi 11.3(包括Patch 1)。
我为自定义的Variant
类型创建了一个“Record Helper”。
我的助手记录正常工作,但编译器不会在编译时验证我的助手调用。
Type
TTest = Type Variant;
TTestHelper = Record Helper for TTest
Public
Function GetV: Variant;
Function AsString: String;
end;
{ TTestHelper }
function TTestHelper.GetV: Variant;
begin
Result := Self;
end;
function TTestHelper.AsString: String;
begin
Result := VarToStr(Self);
end;
//Simple button click
procedure TForm5.Button1Click(Sender: TObject);
var
V: TTest;
begin
V := 'test';
V := V.GetV; //Works as intended
V := V.fopergkergprgkergtk4k3tp3gkg3p; //Compiles without any issue, but of course it gives an "Invalid Variant Operation" when I press the button.
end;
为什么编译器可以编译明显无用的代码,以及为什么我的代码完成窗口不显示任何我的方法(GetV
和AsString
)?
英文:
Using Delphi 11.3 (including Patch 1).
I created a Record Helper
for a custom Variant
type.
My helper record is working, but the compiler doesn't validate my helper call on compile.
Type
TTest = Type Variant;
TTestHelper = Record Helper for TTest
Public
Function GetV: Variant;
Function AsString: String;
end;
{ TTestHelper }
function TTestHelper.GetV: Variant;
begin
Result := Self;
end;
function TTestHelper.AsString: String;
begin
Result := VarToStr(Self);
end;
//Simple button clik
procedure TForm5.Button1Click(Sender: TObject);
var
V: TTest;
begin
V := 'test';
V := V.GetV; //Works as intended
V := V.fopergkergprgkergtk4k3tp3gkg3p; //Compiles without any issue, but of course it gives an "Invalid Variant Operation" when I press the button.
end;
How can it be that the compiler compiles code that is obviously rubbish, and why is my Code Completion window not showing any of my methods (GetV
and AsString
)?
答案1
得分: 4
这是“Variant”的一个特性。
一个“Variant”可以包含不同的内容,包括对COM对象的“IDispatch”接口,该接口在运行时而不是在编译时“延迟绑定”到函数/属性。一个COM对象可能提供一个名为“function fopergkergprgkergtk4k3tp3gkg3p”的函数,这只有在运行时才能检测到,因此编译器允许在“Variant”上的“.”之后的所有内容进行编译,它将在运行时解析,因此可能在运行时成功或失败。
英文:
> How can it be that the compiler compiles code that is obviously rubbish
That is a feature of Variant
.
A Variant
can contain different things, including an IDispatch
interface to a COM object that "late-binds" to functions/properties at runtime instead of at compile-time. A COM object might provide a function fopergkergprgkergtk4k3tp3gkg3p
that may only be detectable at runtime, so the compiler allows everything after .
on a Variant
to compile, and it will be resolved at runtime, so it might succeed or fail at runtime.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论