C# 如何将 String 转换为 Int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1019793/
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
How can I convert String to Int?
提问by turki2009
I have a TextBoxD1.Text
and I want to convert it to an int
to store it in a database.
我有一个TextBoxD1.Text
,我想将它转换为一个int
以将其存储在数据库中。
How can I do this?
我怎样才能做到这一点?
采纳答案by Andrew Hare
Try this:
尝试这个:
int x = Int32.Parse(TextBoxD1.Text);
or better yet:
或者更好:
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
Also, since Int32.TryParse
returns a bool
you can use its return value to make decisions about the results of the parsing attempt:
此外,由于Int32.TryParse
返回 abool
您可以使用其返回值来决定解析尝试的结果:
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
If you are curious, the difference between Parse
and TryParse
is best summed up like this:
如果您很好奇,最好将Parse
和之间的区别TryParse
总结如下:
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. - MSDN
TryParse 方法与 Parse 方法类似,只是 TryParse 方法在转换失败时不会抛出异常。它消除了在 s 无效且无法成功解析的情况下使用异常处理来测试 FormatException 的需要。- MSDN
回答by Babak Naffas
Convert.ToInt32( TextBoxD1.Text );
Use this if you feel confident that the contents of the text box is a valid int
. A safer option is
如果您确信文本框的内容是有效的int
. 更安全的选择是
int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );
This will provide you with some default value you can use. Int32.TryParse
also returns a Boolean value indicating whether it was able to parse or not, so you can even use it as the condition of an if
statement.
这将为您提供一些您可以使用的默认值。Int32.TryParse
还返回一个布尔值,指示它是否能够解析,因此您甚至可以将其用作if
语句的条件。
if( Int32.TryParse( TextBoxD1.Text, out val ){
DoSomething(..);
} else {
HandleBadInput(..);
}
回答by n8wrl
int.TryParse()
It won't throw if the text is not numeric.
如果文本不是数字,它不会抛出。
回答by Jacob
You need to parse the string, and you also need to ensure that it is truly in the format of an integer.
您需要解析字符串,并且您还需要确保它是真正的整数格式。
The easiest way is this:
最简单的方法是这样的:
int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
// Code for if the string was valid
}
else
{
// Code for if the string was invalid
}
回答by Andre Kraemer
int myInt = int.Parse(TextBoxD1.Text)
Another way would be:
另一种方法是:
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
The difference between the two is that the first one would throw an exception if the value in your textbox can't be converted, whereas the second one would just return false.
两者之间的区别在于,如果无法转换文本框中的值,第一个会引发异常,而第二个只会返回 false。
回答by JeffH
As explained in the TryParse documentation, TryParse() returns a Boolean which indicates that a valid number was found:
如TryParse 文档中所述,TryParse() 返回一个布尔值,表示已找到有效数字:
bool success = Int32.TryParse(TextBoxD1.Text, out val);
if (success)
{
// Put val in database
}
else
{
// Handle the case that the string doesn't contain a valid number
}
回答by jorelli
int x = 0;
int.TryParse(TextBoxD1.Text, out x);
The TryParse statement returns a boolean representing whether the parse has succeeded or not. If it succeeded, the parsed value is stored into the second parameter.
TryParse 语句返回一个布尔值,表示解析是否成功。如果成功,则将解析的值存储到第二个参数中。
See Int32.TryParse Method (String, Int32)for more detailed information.
有关更多详细信息,请参阅Int32.TryParse 方法 (String, Int32)。
回答by deepu
int i = Convert.ToInt32(TextBoxD1.Text);
回答by Misha Zaslavsky
You also may use an extension method, so it will be more readable (although everybody is already used to the regular Parse functions).
您也可以使用扩展方法,因此它会更具可读性(尽管每个人都已经习惯了常规的 Parse 函数)。
public static class StringExtensions
{
/// <summary>
/// Converts a string to int.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The converted integer.</returns>
public static int ParseToInt32(this string value)
{
return int.Parse(value);
}
/// <summary>
/// Checks whether the value is integer.
/// </summary>
/// <param name="value">The string to check.</param>
/// <param name="result">The out int parameter.</param>
/// <returns>true if the value is an integer; otherwise, false.</returns>
public static bool TryParseToInt32(this string value, out int result)
{
return int.TryParse(value, out result);
}
}
And then you can call it that way:
然后你可以这样称呼它:
If you are sure that your string is an integer, like "50".
int num = TextBoxD1.Text.ParseToInt32();
If you are not sure and want to prevent crashes.
int num; if (TextBoxD1.Text.TryParseToInt32(out num)) { //The parse was successful, the num has the parsed value. }
如果您确定您的字符串是一个整数,例如“50”。
int num = TextBoxD1.Text.ParseToInt32();
如果您不确定并希望防止崩溃。
int num; if (TextBoxD1.Text.TryParseToInt32(out num)) { //The parse was successful, the num has the parsed value. }
To make it more dynamic, so you can parse it also to double, float, etc., you can make a generic extension.
为了使其更具动态性,以便您也可以将其解析为 double、float 等,您可以进行通用扩展。
回答by Salim Latif Waigaonkar
Enjoy it...
好好享受...
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);