我想知道是否有一种“安全”的方法可以将对象转换为 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);
}
但是IConvertible
的ToInt32
方法是不能取消的。因此,如果无法转换值,则无法避免异常。
或者二:有没有办法检查对象是否包含隐式运算符?
这很差:
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/