简体   繁体   English

在C#中检查字符串并将其转换为int的最佳方法

[英]Best way to check string and convert to int in c#

Please help me to improve my code. 请帮助我改善代码。 The idea is: if string is ok then convert to int 这个想法是:如果字符串可以,则转换为int

1- it does check just null or blank string 1-它只检查空或空字符串

int t=0;
 if(!string.IsNullOrEmpty(textbox1.text.trim())
     t= int.Parse(textbox1.text.trim());

2- 2

if(int.tryparse(textbox1.text.trim(), out t)      
   t=int.Parse(textbox1.text.trim());

or shortif 或简称

 return string.IsNullOrEmpty(textbox1.text.trim()) ? 0 :  int.Parse(textbox1.text.trim());

is there other better way? 还有其他更好的方法吗?

The correct way to get user input and convert it to integers is through the Int32.TryParse method. 获取用户输入并将其转换为整数的正确方法是通过Int32.TryParse方法。 This method has the advantage to not throw a costly exception if the input is wrong (like Parse or Convert.ToInt32) but returns true or false allowing you to display a meaningful error message to your user. 此方法的优点是,如果输入错误(例如Parse或Convert.ToInt32),则不会引发代价高昂的异常,但会返回true或false,从而使您可以向用户显示有意义的错误消息。

int t;
if(Int32.TryParse(textbox1.Text, out t)
{
  // t has ben set with the integer converted
  // add here the code that uses the t variable
}
else
{
  // textbox1.Text doesn't contain a valid integer
  // Add here a message to your users about the wrong input....
  // (if needed)
}

Notice that textbox1.Text is never null so you don't need to explicitly check for it. 请注意,textbox1.Text永远不会为null,因此您无需显式检查它。 Of couse I assume that this textbox1 is a TextBox control defined in your InitializeComponent call and thus is not null by itself. 当然,我假设此textbox1是在InitializeComponent调用中定义的TextBox控件,因此其自身不为null。

int t = 0;
int.TryParse(textbox1?.Text?.Trim(), out t);
int i = 0;

Int32.TryParse(TextBox1.Text, out i);

Yes. 是。 We need to Check whether TryParse returns true or Not. 我们需要检查TryParse是否返回true或Not。 if true then it succeeds & false if any error occurs.The TryParse will return 0 for both if the TryParse is failed or actual string value is 0. 如果为true,则成功;如果发生任何错误,则为false。如果TryParse失败或实际字符串值为0,则TryParse都将返回0。

string s2 = "13.3";
int i;

//i = Convert.ToInt32(s2);                   // Run Time Error
Console.WriteLine(int.TryParse(s2, out i));  // False
Console.WriteLine(i);                        // Output will be 0

string s3 = "Hello";
//i = Convert.ToInt32(s2);                  // Run Time Error
Console.WriteLine(int.TryParse(s3, out i)); // False
Console.WriteLine(i);                       // Output will be 0

string s1 = null;
Console.WriteLine(int.TryParse(s1, out i));  // False
Console.WriteLine(i);                        // Output will be 0

string s4 = "0";      
Console.WriteLine(int.TryParse(s4, out i));  // return True
Console.WriteLine(i);                        // Output will be 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM