2012-01-30 82 views
0

我想查看嘗試轉換是否可以將用戶輸入的答案轉換爲我指定的類型。無法比較類型

這是我有:

Dim t as type = GetType(myType) 
Dim ans = console.readline() 

If TryCast(ans, t) <> Nothing Then ... 'Doesn't work` 

在智能感知甚至不顯示T上方的例子。如何使它工作?

回答

0

我猜你想檢查用戶的輸入是字符串,int,bool,日期等...

所以,如果你想轉換readline()特定類型,你可以做到以下幾點:

If myType.GetType Is GetType(Integer) Then 
    'your code... 
ElseIf myType.GetType Is GetType(DateTime) Then 
    .... 

丹尼斯的答覆也是一個不錯的想法..

希望幫助!

0

您不需要獲取類型。如果ans類型爲string可以轉換爲myType,那麼以下內容應該可以工作。當然,如果不知道myType的執行情況,我不知道鑄件是否可以工作。

Dim ans = console.readline() 
If TryCast(ans, myType) <> Nothing Then 
    ... 
End If 
0

我不知道,如果你與你的了的myType等問題存在,但你用是測試,沒有:

If myObject Is Nothing Then 

If myObject IsNot Nothing Then 
0

我想看看如果嘗試轉換可以將用戶輸入的答案轉換爲我指定的類型 。

在這種情況下,你不想Cast,你想Parse用戶的答案。比方說,一個用戶輸入一個字符串的值,並且你想將它解析爲一個Integer,你應該這樣做:

Dim userInput As String = "123" 
Dim intValue As Integer 
If Integer.TryParse(userInput, intValue) Then 
    'User's answer is an int 
End If