【发布时间】:2015-11-18 08:21:20
【问题描述】:
下面的 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.
但是,在一个结构相似的 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();
}
}
}
由于 TObject.Free 使用这种风格,似乎“支持”在 Delphi 中对 nil 引用调用方法。这是真的 ? (假设在if Self = nil 分支中,不会访问任何实例字段。)
【问题讨论】:
-
@HenkHolterman 非常感谢您提供的宝贵信息!