2017-07-18 67 views
0

我已經做了一些代碼,以返回到網站的博客部分的概述頁面。下面代碼中的變量OverviewLink1OverviewLink2都是HtmlAnchor s,並將設置Href屬性等於我所做的變量state如何在VB中將對象轉換爲字符串變量?

屬性HttpContext.Current.Application獲取當前HTTP請求的System.Web.HttpApplicationState對象。

Dim state As HttpApplicationState = HttpContext.Current.Application(component.type & "-" & webId & "-" & langId) 
OverviewLink1.HRef = state ' <-- Error happens on this line 
OverviewLink2.HRef = HttpContext.Current.Application(component.type & "-" & webId & "-" & langId) 

此代碼給在第二行上的誤差:HttpApplicationState類型的

值不能被轉換爲String

第三行不會給出錯誤。 Try it here in this fiddle.現在我有一些問題:

  1. 第三條線如何工作?
  2. 在VB中如何投射一般變量的變量?
  3. 如何預防這種情況?因爲我來自C#,這種情況是不可能的。

我使用VB與ASP.NET Webform (CMS是Liquifi)應用程序。

PS:的由CMS Liquifi使用的變量component.typewebIdlangId是變量分別獲取組件(類型String的名稱,該網站的ID (一個網站可以有多個外觀)(類型Integer和站點(類型Integer的語言)

更新:

我也試過這個代碼

Dim state As String = HttpContext.Current.Application(component.type & "-" & webId & "-" & langId) 
OverviewLink1.HRef = state 
OverviewLink2.HRef = state 

,這工作得很好但是HttpContext.Current.Application返回HttpApplicationState而不是字符串,但有一個鑄鐵發生。爲什麼?

+0

你確定第三行有效嗎? – Pikoh

+0

@Pikoh:是的,我敢肯定,看到小提琴:https://dotnetfiddle.net/deU9N0 –

+0

那個小提琴沒有說什麼,因爲'HttpContext.Current'是'Nothing',所以返回的類型不是'HttpAplicationState' – Pikoh

回答

1

主要問題是,在VB.NET中,默認情況下打開類型的靈活自動轉換,這可能會帶來非常意外的結果和運行時錯誤。特別是如果你來自C#這樣嚴格的語言。

我建議大家通過設置把這個autoshit關每個項目:
項目屬性 - >編譯 - >選項嚴格在

現在,它就會哭每次都會嘗試分配的東西其他不兼容的東西。

2

我認爲這個問題是你認爲HttpContext.Current.Application返回一個HttpApplicationState。如果你沒有給它任何參數,這是正確的,但如果你傳遞一個參數,它會返回一個Object(與該鍵匹配的項目)。

在C#中,您的代碼的第三行不會編譯,因爲它會執行嚴格的類型檢查,但在VB.net中(默認情況下)它不會,所以它編譯並在運行時嘗試將該Object轉換爲String。你舉的例子是類似下面的代碼:

Dim s As Object = "A" 
'Both of the next two lines compiles 
Dim str As String = s ' it works 
Dim str2 As Integer = s ' Would fail in runtime 

如果你施放HttpContext.Current.Application(key)一個Object,它也將編譯:

Dim state As HttpApplicationState = HttpContext.Current.Application(component.type & "-" & webId & "-" & langId) 
Dim state2 As Object = HttpContext.Current.Application("blog-1-1") 
Dim str3 as String= state 'Compile error, you can't convert HttpApplicationState to String 
Dim str4 as String = state2 'It compiles, would give a runtime error 

你會使用Option Strict標誌解決這個問題。這樣你的第三行就不會編譯,因爲VB.NET會像C#那樣進行嚴格的類型檢查。