问题描述
我想知道是否有一种安全"的方式将对象转换为 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);
}
但是IConvertible
的ToInt32
方法无法取消.所以如果不能转换值,就无法避免异常.
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... 避免异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!