分配给数字的空值 [英] null value assigned to numbers

查看:55
本文介绍了分配给数字的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此语句将显示一个带有空消息的消息框.

This statement will show a message box with empty message.

string i="";
messagebox.show(i.tostring());


如果我是int,我如何获得相同的行为?
我希望这样的事情


How I can get the same behavior if i is int?
I expect something like this

int I="";
messagebox.show(I.tostring());


我尝试了很多方法,但是没有任何效果.我希望有一些简单的解决方案.


I tried many ways, but nothing worked. There is some simple solution I hope.

推荐答案

对不起,我认为您有一个int并希望能够存储是否已设置它,即是否可以为null.

如果您有一个DataGridViewCell并希望将其设置为空白,但是单元格类型是整数,则不能这样做-没有有效的空"整数.您还需要更改单元格类型:

Sorry I thought that you had an int that you want to also be able to store whether it was set or not, i.e. nullable or not.

If you have a DataGridViewCell and you want to make it blank, but the cell type is an integer, you can''t do this - there is no valid ''empty'' integer. You''ll need to change the cell type as well:

DataGridViewCell someCell; // = your code here.

// Set the cell value type to a string so that we can clear it.
someCell.ValueType = typeof(string);

// Set the cell data to an empty string.
someCell.Value = string.Empty;




请非常小心-如果将数据绑定为int类型,则永远不要进入int刚刚消失的状态.例如,如果要使值0看起来为空,则可以使用自定义格式设置:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx [ ^ ]

例如,您可以说当该值为零时,它会将其格式化为空字符串-这样基础数据仍然是一致的.




Just be really careful - if you''re databound to an int type then you should never get to the state where the int has just disappeared. If, for example, you want to make the value 0 look empty, then you can do this with custom formatting:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx[^]

For example you can say that when the value is zero, it formats it as an empty string - this way the underlying data is still consistent.


除了其他答案,我还应该添加: string value = ""不等于null,您可以轻松地证明它.您可能已经写过string value = null.

顺便说一句,请避免使用任何立即常量,尤其是字符串类型的常量.我认为文字null很好,但是出于可维护性的原因,"当然不是.如果您确实想要空字符串而不是null,请始终使用string.Empty.

-SA
In addition to other answers, I should add: string value = "" does not equal to null, you can easily proof it. You could have written string value = null.

By the way, avoid using any immediate constants, especially of string type. I think the literal null is perfectly fine, but "" is certainly not, for maintainability reasons. If you really want empty string and not null, always use string.Empty.

—SA


您必须使用
Nullable<int></int>

int?

-这使它成为一个整数,也可以具有空值!

- this makes it an int that can also have a null value!

int? i = null;

String s = !(i.HasValue) ? "" : i.ToString(); // MRB: used ! operator (logical not) instead of '== false'



基本阅读: http://msdn.microsoft.com/zh-cn/library/1t3y8s4s(v = VS.100).aspx [ ^ ]



Essential reading: http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=VS.100).aspx[^]


这篇关于分配给数字的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆