我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。

我该怎么做?


当前回答

虽然我同意使用TryParse方法,但很多人不喜欢使用out参数(包括我自己)。在C#中添加了元组支持后,另一种方法是创建一个扩展方法,该方法将限制您使用单个实例的次数:

public static class StringExtensions
{
    public static (int result, bool canParse) TryParse(this string s)
    {
        int res;
        var valid = int.TryParse(s, out res);
        return (result: res, canParse: valid);
    }
}

(来源:C#如何将字符串转换为int)

其他回答

您可以编写自己的扩展方法

public static class IntegerExtensions
{
    public static int ParseInt(this string value, int defaultValue = 0)
    {
        int parsedValue;
        if (int.TryParse(value, out parsedValue))
        {
            return parsedValue;
        }

        return defaultValue;
    }

    public static int? ParseNullableInt(this string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return null;
        }

        return value.ParseInt();
    }
}

代码中的任何地方都可以调用

int myNumber = someString.ParseInt(); // Returns value or 0
int age = someString.ParseInt(18); // With default value 18
int? userId = someString.ParseNullableInt(); // Returns value or null

在这个具体的例子中

int yourValue = TextBoxD1.Text.ParseInt();

您需要解析字符串,还需要确保它确实是整数格式。

最简单的方法是:

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
}
//May be quite some time ago but I just want throw in some line for any one who may still need it

int intValue;
string strValue = "2021";

try
{
    intValue = Convert.ToInt32(strValue);
}
catch
{
    //Default Value if conversion fails OR return specified error
    // Example 
    intValue = 2000;
}
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;

如TryParse文档中所述,TryPars()返回一个布尔值,表示找到了一个有效的数字:

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
}