关于VarIsNull,VarIsEmpty

csdn_bob 2011-05-05 06:31:54
procedure TForm1.btn1Click(Sender: TObject);
var
a:Variant;
begin
if VarIsNull(a) then
ShowMessage('VarIsNull=true');
if VarIsEmpty(a) then
ShowMessage('VarIsEmpty=true'); //这里执行
a:=vaNull;
if VarIsNull(a) then
ShowMessage('a:=vaNull,VarIsNull=true');
if VarIsEmpty(a) then
ShowMessage('a:=vaNull,VarIsEmpty=true');
a:=Unassigned;
if VarIsNull(a) then
ShowMessage('a:=Unassigned,VarIsNull=true');
if VarIsEmpty(a) then
ShowMessage('a:=Unassigned,VarIsEmpty=true'); //这里执行
end;

测试环境,win7,64位,delphi7

大家发上自己的测试情况 看看。。
...全文
277 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
csdn_bob 2011-05-06
  • 打赏
  • 举报
回复
谢谢各位,让在下理解了vaNull,nil,Null的函义。

procedure TForm1.btn1Click(Sender: TObject);
var
a:Variant;
begin
if VarIsNull(a) then
ShowMessage('VarIsNull=true');
if VarIsEmpty(a) then
ShowMessage('VarIsEmpty=true'); //执行

a:=vaNull;
if VarIsNull(a) then
ShowMessage('a:=vaNull,VarIsNull=true');
if VarIsEmpty(a) then
ShowMessage('a:=vaNull,VarIsEmpty=true');

a:=Unassigned;
if VarIsNull(a) then
ShowMessage('a:=Unassigned,VarIsNull=true');
if VarIsEmpty(a) then
ShowMessage('a:=Unassigned,VarIsEmpty=true'); //执行

a:=null;
if VarIsNull(a) then
ShowMessage('a:=null,VarIsNull=true'); //执行
if VarIsEmpty(a) then
ShowMessage('a:=null,VarIsEmpty=true');

end;


xinghun61 2011-05-05
  • 打赏
  • 举报
回复
不知楼主这样测试的目的是干嘛,不过,从Delphi的源码来看,我们可以把Null、Unassigned、VarIsNull、VarIsEmpty看作是对VType结构的设置和判断(Variant其实是TVarData类型的record),具体如下:
Null:VType := varNull{varNull的值为1}
Unassigned:VType := varEmpty{varEmpty的值为0}
VarIsNull:Result := VType = varNull
VarIsEmpty:Result := VType = varEmpty
另外,当为Variant类型的局部变量开辟内存空间时,似乎将其值填充为0(这个是从汇编代码中猜测的,Delphi官方文档中没看到)
有了上面的说明,楼主测试的结果就容易理解了——
刚进去,由于VType为0,因此,VarIsEmpty成立;
将a设为vaNull,由于vaNull为枚举类型,值为0,Delphi将其视为整数处理,将VType设为varSmallint(这个具体没测试,还有可能为varInteger或varShortInt吧),因此,两个判断都不成立(其实,如果这时将a的VType设为varNull,例如,TVarData(v).VType := varNull,则VarIsNull会成立);
而将a设为Unassigned后的结果就留给楼主自己吧,呵呵。
Oraclers 2011-05-05
  • 打赏
  • 举报
回复
a:=vaNull;
这里应是:
a := Null;
Oraclers 2011-05-05
  • 打赏
  • 举报
回复
VarIsNull returns true if the given variant contains the value Null. If the variant contains any other value, the function result is false.

Note: Do not confuse a Null variant with an unassigned variant. A Null variant is still assigned, but has the value Null. Unlike unassigned variants, Null variants can be used in expressions and can be converted to other types of variants.
看上面的Delphi帮助。
VarIsNull是确定Variant变量是不是包含一个NULL值,这个变量是有值的,不过只是NULL,这时这个函数返回True;
VarIsEmpty是确定Variant变量是不是有值,没有赋过值,或者是“赋”了一个“Unassigned”,这时这个函数返回True;

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧