2013-05-16 48 views
3

我希望將外部緩存中的對象安全地轉換爲Integer類型。將對象轉換爲整數的最佳方法

我似乎可以做到這一點的唯一方法是try catch塊內,像這樣:

Try 
    Return Convert.ToInt32(obj) 
Catch 
    'do nothing 
End Try 

我討厭寫catch語句這樣。

有沒有更好的方法?

我曾嘗試:

TryCast(Object, Int32) 

無效(必須是引用類型)

Int32.TryParse(Object, result) 

無效(必須是一個字符串類型)

UPDATE

我喜歡Jodrell發表的評論 - 這個woul ð使我的代碼看起來是這樣的:

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 
+2

此對象來自哪裏,它包含什麼? – SWeko

+0

它來自外部緩存,它包含一個整數。我不能相信它不會是畸形的數據blob。 –

+0

你認爲'TryCast'發生了什麼? – Jodrell

回答

2

Unesscessary轉換爲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 
+0

這不起作用 - 只能使用引用類型 –

+0

@ geo1701您是對的,可以爲Nullable '是一個結構。 – Jodrell

+0

@ geo1701修正了錯誤。 – Jodrell

3

澄清:這個問題最初是標記;以下適用到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 
} 
+0

是這個vb。淨? – Jodrell

+0

@Jodrell最初由OP添加的標籤包括C# - 所以我認爲C#是可以接受的http://stackoverflow.com/posts/16582146/revisions –

+0

這似乎過於複雜 –

1

最簡單的是

Int32.TryParse(anObject.ToString, result) 

每個對象都有一個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代碼

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代碼如下

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讓我發現新的東西。

+0

如果您不在IDE中,那麼異常實際上並不是那麼昂貴 –

+0

我不喜歡轉換爲字符串的想法 –

0

這個工程:應避免

Int32.TryParse(a.ToString(), out b); 
相關問題