C# 字符串和数字条件的最佳实践
我只是想知道如何写出一个必须用字符串表示的数字 例如:C# 字符串和数字条件的最佳实践,c#,string,integer,C#,String,Integer,我只是想知道如何写出一个必须用字符串表示的数字 例如: if (SelectedItem.Value == 0.ToString()) ... 或 或 或 就一次测试而言,我个人认为 if (SelectedItem.Value == "0") 它没有大惊小怪,没有仪式——它准确地表达了你想要做的事情 另一方面,如果我有一个应该是数字的值,然后我会根据该数字做出反应,我会使用: int value; // Possibly use the invariant culture here; it
if (SelectedItem.Value == 0.ToString()) ...
或
或
或
就一次测试而言,我个人认为
if (SelectedItem.Value == "0")
它没有大惊小怪,没有仪式——它准确地表达了你想要做的事情
另一方面,如果我有一个应该是数字的值,然后我会根据该数字做出反应,我会使用:
int value;
// Possibly use the invariant culture here; it depends on the situation
if (!int.TryParse(SelectedItem.Value, out value))
{
// Throw exception or whatever
}
// Now do everything with the number directly instead of the string
使用
如果这个值是一个整数,这是它应该自然使用的,那么我将把它解析为一个int-也就是说,使用最适合数据含义的类型
例如,通常下拉列表都是从数据库查找表中填充的——如果它将项键存储为整数,那么我认为您应该始终将其作为一个整数处理。同样,如果所选项目的键再次存储在数据库中,则无论如何都需要在某个点将其转换为int。@Asad Butt-为什么这在这里很重要?
if (Int.Parse(SelectedItem.Value) == 0)
if (SelectedItem.Value == "0")
int value;
// Possibly use the invariant culture here; it depends on the situation
if (!int.TryParse(SelectedItem.Value, out value))
{
// Throw exception or whatever
}
// Now do everything with the number directly instead of the string
string value = "123";
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
...