c# - 有没有尝试 Convert.ToInt32 ...避免异常

标签 c# type-conversion

我想知道是否有一种“安全”的方法可以将对象转换为 int,从而避免异常。

我正在寻找类似public static bool TryToInt32(object value, out int result);

我知道我可以做这样的事情:

public static bool TryToInt32(object value, out int result)
{
    try
    {
        result = Convert.ToInt32(value);
        return true;
    }
    catch
    {
        result = 0;
        return false;
    }
}

但我宁愿避免异常,因为它们会减慢进程。

我认为这样更优雅,但仍然“廉价”:

public static bool TryToInt32(object value, out int result)
{
    if (value == null)
    {
        result = 0;
        return false;
    }

    return int.TryParse(value.ToString(), out result);
}

有没有人有更好的想法?

更新:

这听起来有点像吹毛求疵,但将对象转换为字符串会迫使实现者创建一个清晰的 ToString() 函数。例如:

public class Percentage
{
    public int Value { get; set; }

    public override string ToString()
    {
        return string.Format("{0}%", Value);
    }
}

Percentage p = new Percentage();
p.Value = 50;

int v;
if (int.TryParse(p.ToString(), out v))
{

}

出错了,我可以在这里做两件事,或者像这样实现IConvertable:

public static bool ToInt32(object value, out int result)
{
    if (value == null)
    {
        result = 0;
        return false;
    }

    if (value is IConvertible)
    {
        result = ((IConvertible)value).ToInt32(Thread.CurrentThread.CurrentCulture);
        return true;
    }

    return int.TryParse(value.ToString(), out result);
}

但是IConvertibleToInt32方法是不能取消的。因此,如果无法转换值,则无法避免异常。

或者二:有没有办法检查对象是否包含隐式运算符?

这很差:

if (value.GetType().GetMethods().FirstOrDefault(method => method.Name == "op_Implicit" && method.ReturnType == typeof(int)) != null)
{
    result = (int)value;
    return true;
}

最佳答案

int variable = 0;
int.TryParse(stringValue, out variable);

如果无法解析,变量将为0。参见http://msdn.microsoft.com/en-us/library/f02979c7.aspx

关于c# - 有没有尝试 Convert.ToInt32 ...避免异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227220/

相关文章:

c++ - 确定最佳转换的 Variadic 模板

C++:如何处理 NULL 值(例如来自数据库)?

java - 如何将小时和分钟添加到java vector 中包含的总分钟数中

c# - Excel-C# : How to read the formulas from a cell?

c# - 数据行到 CSV 行 C#

c# - 为什么即使我的类型实现了 IDisposable,Using 语句也会出错?

ios - Objective-C:在不损失精度的情况下将 float 转换为 int64_t

c# - 实现特定接口(interface)的类型集合

c# - 设置 Moq 以忽略虚拟方法

Python "safe"eval(字符串到 bool/int/float/None/string)