vb.net .NET 2.0 中带前导零的格式数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26687805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format number with leading zeroes in .NET 2.0
提问by Wine Too
I have problem to format numbers and convert it to string with leading zeroes when application uses NET framework 2.0 with Visual Basic.
当应用程序将 NET Framework 2.0 与 Visual Basic 一起使用时,我在格式化数字并将其转换为带前导零的字符串时遇到问题。
I try:
我尝试:
Dim myNum = 12
Dim myStr as String
Dim myStr = myNum.ToString("0000")
or
Dim myStr = myNum.ToString("D4")
... in order to get wanted string: 0012
...为了得到想要的字符串:0012
Please help to solve this.
请帮助解决这个问题。
回答by Hans Passant
You have an old version of Visual Studio, one that doesn't have Option Inferyet. Or it isn't turned on. That makes the myNumidentifier a variable of type Object.
你有一个旧版本的 Visual Studio,一个还Option Infer没有。或者它没有打开。这使得myNum标识符成为类型的变量Object。
So your code tries to call the Object.ToString() method. Which does not have an overload that takes an argument. The compiler now tries to make hay of your code and can only do so by treating ("0000") or ("D4") as an array index expression. Indexing the string that's returned by Object.ToString(). That has pretty funny side effects, to put it mildly. A string like "0000" is not a valid index expression, the compiler generates code to automatically convert it to an Integer. That works for "0000", converted to 0 and the result is a character, just "1"c. Converting "D4" to an integer does not work so well of course, that's a loud Kaboom!
所以您的代码尝试调用 Object.ToString() 方法。它没有带参数的重载。编译器现在会尝试处理您的代码,并且只能通过将 ("0000") 或 ("D4") 视为数组索引表达式来实现。索引 Object.ToString() 返回的字符串。委婉地说,这有非常有趣的副作用。像“0000”这样的字符串不是有效的索引表达式,编译器会生成代码以自动将其转换为整数。这适用于“0000”,转换为0,结果是一个字符,只是“1”c。将“D4”转换为整数当然效果不佳,这是一个响亮的Kaboom!
The solution is a very simple one, just name the type of the variable explicitly:
解决方法很简单,只需显式命名变量的类型:
Dim myNum As Integer = 12
Dim myStr = myNum.ToString("D4") '' Fine
VB.NET's support for dynamic typing is pretty in/famous. Meant to help new programmers getting started, it in fact is an advanced technique given the myriad ways it can behave in veryunexpected ways.
VB.NET 对动态类型的支持非常著名。旨在帮助新程序员入门,它实际上是一种先进的技术,因为它可以以非常出乎意料的方式表现出无数种方式。
The universal advice is always the same. Let the compiler help you catch mistakes like this. Put this at the top of your source code file:
普遍的建议总是一样的。让编译器帮助您捕捉这样的错误。把它放在你的源代码文件的顶部:
Option Strict On

