文本框是否将全数字文本保存为长文本或字符串?
我和我的队友就此进行了简短的讨论。他说,如果我在文本框中输入一个数字,并尝试稍后使用 textbox.text 或 val(textbox.text) 使用该值,我将不需要将该值解析为整数。据他介绍,如果文本属性值都是数字,则可以直接获取整数值,而不是字符串。
因此,如果我有 textBox1.Text = "12345"
,那么下次如果我使用 intABC = textBox1.Text
,它就不会抛出错误。对吗? C# 或其他 .Net 语言是否执行此隐式转换?另外,代码会将 "12345"
存储为字符串还是整数?这个值需要多少内存,5 个字符需要 5 个字节,还是一个整数需要 2 个字节?
I have a brief discussion with my teammate regarding this. He says, if I enter a number in textbox, and try to use the value later on using textbox.text or val(textbox.text), I will not need to parse the value to integer. According to him, if the text attribute value is all number, you can directly get the value as integer, instead of string.
So, if I have textBox1.Text = "12345"
, then next time, if I use, intABC = textBox1.Text
, it will not throw an error. Is it right? Does C# or other .Net language does this implicit conversion? Also, will the code store "12345"
as string or integer? And how much memory will this value take, 5bytes for 5 characters or 2bytes for an integer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
TextBox.Text
将文本保留为简单字符串,它不关心字符串的真正“含义”。然后,如果你想取回你的号码,你需要解析字符串,因此不允许隐式或显式转换为 int (或者更好,如果你这样做,它会抛出异常......)。
关于大小,该文本存储为 UNICODE (UTF-16) 字符串,因此每个字符有 2 到 4 个字节(取决于字符)。
您可以使用以下代码轻松测量大小(只是字符串的大小,没有由于参考大小等造成的开销):
要查找有关字符串、unicode 和编码的更多信息,请查看 此处,此处 或 这里。
TextBox.Text
keeps the text as a simple string, it doesn't care about the real "meaning" of the string.Then, if you want to have your number back, you need to parse the string, hence neither implicit nor explicit cast to int is allowed (or better, it will throw an exception if you do it...).
About the size, that text is stored as an UNICODE (UTF-16) string, hence from 2 to 4 bytes per character (depending on the character).
You can easily measure the size (just the size of the string, without the overhead due to reference size etc.) using the following code:
To find more info about strings, unicode and encodings have a look here, here or here .
你的朋友错了,它会让编译器不高兴,编译器甚至不会自动为你转换它。 TextBox 的 Text 属性是字符串类型。检查此
http://msdn.microsoft .com/en-us/library/system.web.ui.webcontrols.textbox.text.aspx
your friend is wrong, it will make the compiler unhappy, the compiler won't even convert it automatically for you. Text property of a TextBox is of type string. check this
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.text.aspx
至于你的其他语言的问题;如果未启用“option strict”,VB.NET 将允许这样做。如果输入不完全是数字,它也将允许这种分配,从而导致运行时异常。
As to your question of other languages; if 'option strict' is not enabled, VB.NET will allow this. It will also allow this assignment if the input is not entirely numeric however, resulting in a runtime exception.
如果您知道只会使用数值,请尝试使用 NumericUpDown 控件。
然后,您可以使用
Value
属性获取/设置数值(十进制)。If you know you will only use numerical values, try using a NumericUpDown control.
You could then get/set the numerical value (decimal) by using the
Value
property.