我希望将对象从外部缓存安全地转换为Integer类型。
我似乎能做到这一点的唯一方法就是在try catch块里面这样:
Try
Return Convert.ToInt32(obj)
Catch
'do nothing
End Try
我讨厌写这样的catch语句。
有更好的方法吗?
我试过了:
TryCast(Object, Int32)
不起作用(必须是参考类型)
Int32.TryParse(Object, result)
不起作用(必须是字符串类型)
更新
我喜欢Jodrell发布的评论 - 这会让我的代码看起来像这样:
Dim cacheObject As Object = GlobalCache.Item(key)
If Not IsNothing(cacheObject) Then
If TypeOf cacheObject Is Int32 Then
Return Convert.ToInt32(cacheObject)
End If
End If
'Otherwise get fresh data from DB:
Return GetDataFromDB
答案 0 :(得分:3)
澄清:问题最初标记为c# vb.net;以下将仅适用于C#(尽管可能已翻译成VB.NET):
如果是方框int
,则:
object o = 1, s = "not an int";
int? i = o as int?; // 1, as a Nullable<int>
int? j = s as int?; // null
如此概括:
object o = ...
int? i = o as int?;
if(i == null) {
// logic for not-an-int
} else {
// logic for is-an-int, via i.Value
}
答案 1 :(得分:2)
应避免不必要地转换为String
。
您可以使用Is
预先检查类型
Dim value As Integer
If TypeOf obj Is Integer Then
value = DirectCast(obj, Integer)
Else
' You have a problem
End If
,或者
你可以在TryCast
上实现这样的变体,
Function BetterTryCast(Of T)(ByVal o As Object, ByRef result As T) As Boolean
Try
result = DirectCast(o, T)
Return True
Catch
result = Nothing
Return False
End Try
End Function
您可以像这样使用
Dim value As Integer
If BetterTryCast(obj, value) Then
// It worked, the value is in value.
End If
答案 2 :(得分:1)
最简单的是
Int32.TryParse(anObject.ToString, result)
每个Object都有一个ToString方法,如果Object不是数字整数,调用Int32.TryParse将避免代价高昂(就性能而言)异常。如果对象不是字符串,结果的值也将为零。
修改即可。 Marc Gravell的回答引起了我的好奇心。对于简单的转换,它的答案看起来很复杂,但它更好吗?所以我试着看一下它的答案产生的IL代码
object o = 1, s = "not an int";
int? i = o as int?; // 1, as a Nullable<int>
int? j = s as int?; // null
IL CODE
IL_0000: ldc.i4.1
IL_0001: box System.Int32
IL_0006: stloc.0 // o
IL_0007: ldstr "not an int"
IL_000C: stloc.1 // s
虽然我的答案产生的IL CODE如下
IL_0000: ldc.i4.1
IL_0001: box System.Int32
IL_0006: stloc.0 // anObject
IL_0007: ldloc.0 // anObject
IL_0008: callvirt System.Object.ToString
IL_000D: ldloca.s 01 // result
IL_000F: call System.Int32.TryParse
Marc的答案肯定是最好的方法。感谢Marc让我发现新的东西。
答案 3 :(得分:0)
这有效:
Int32.TryParse(a.ToString(), out b);