以下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引用上的方法似乎是"支持"的.这是真的 ?(假设在 …
为什么这段代码不会崩溃?T没有.它是如何可以访问Caption是否T是nil?
procedure Crash;
VAR T: TButton;
begin
T:= NIL;
T.Caption:= ''; <---------- this works
end;
Run Code Online (Sandbox Code Playgroud) 我认为这是“最佳实践”类别的问题:
我有一个自定义控件-一种可容纳一些面板的网格。面板之一是当前活动面板(最后一个单击)。
TMyGrid = class (TSomeKindOfGrid)
published
property CurrentPanel: TPanel read getCurPanel write setCurPanel;
end;
Run Code Online (Sandbox Code Playgroud)
我的问题是:如果在某个时候有人要求CurrentPanel且网格为空,应该getCurPanel返回NIL还是引发异常?
getCurPanel返回NIL,则我必须在每次/每次致电时都要检查NIL CurrentPanel。呼叫者也有可能忘记检查NIL。好吧,因为它将尝试访问NIL对象,所以不会发生任何“不良”情况。该程序将很好地崩溃。我得到了堆栈跟踪。 getCurPanel,我只会在一个地方进行检查(是的,我很懒)。