以下Delphi程序在nil引用时调用方法并运行正常.
program Project1;
{$APPTYPE CONSOLE}
type
TX = class
function Str: string;
end;
function TX.Str: string;
begin
if Self = nil then begin
Result := 'nil'
end else begin
Result := 'not nil'
end;
end;
begin
Writeln(TX(nil).Str);
Readln;
end.
Run Code Online (Sandbox Code Playgroud)
但是,在结构相似的C#程序中,System.NullReferenceException
将会提出,这似乎是正确的做法.
namespace ConsoleApplication1
{
class TX
{
public string Str()
{
if (this == null) { return "null"; }
return "not null";
}
}
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(((TX)null).Str());
System.Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
因为TObject.Free使用这样的样式,所以在Delphi中调用nil引用上的方法似乎是"支持"的.这是真的 ?(假设在if Self = nil
分支中,不会访问任何实例字段.)
Dav*_*nan 18
根据nil
以下规则在引用上调用方法是合理的:
nil
则没有运行时类型.相比之下,非虚拟的非动态方法在编译时受到约束.Self
,例如将其与之进行比较nil
.Self
是nil
,那么你不能引用任何实例变量. 归档时间: |
|
查看次数: |
473 次 |
最近记录: |