有没有尝试 Convert.ToInt32... 避免异常

Is there a try Convert.ToInt32... avoiding exceptions(有没有尝试 Convert.ToInt32... 避免异常)
本文介绍了有没有尝试 Convert.ToInt32... 避免异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种安全"的方式将对象转换为 int,避免异常.

I'd like to know if there is a "safe" way to convert an object to an int, avoiding exceptions.

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

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

I know I could make something like this:

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

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

But I'd rather avoid exceptions, because they are slowing down the process.

我觉得这样更优雅,但还是便宜":

I think this is more elegant, but it's still "cheap":

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

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

有人有更好的想法吗?

更新:

这听起来有点像扯皮,但是将对象转换为字符串会强制实现者创建一个清晰的 ToString() 函数.例如:

This sounds a little like splitting hairs, but converting an object to string forces the implementer to create a clear ToString() function. For example:

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:

This goes wrong, I can do two things here, or implement the IConvertable like this:

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方法无法取消.所以如果不能转换值,就无法避免异常.

But the ToInt32 method of the IConvertible cannot be canceled. So if it's not possible to convert the value, an exception cannot be avoided.

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

Or two: Is there a way to check if the object contains a implicit operator?

这很糟糕:

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

If it can't be parsed, the variable will be 0. See http://msdn.microsoft.com/en-us/library/f02979c7.aspx

这篇关于有没有尝试 Convert.ToInt32... 避免异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)