2017-07-18 64 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#那样进行严格的类型检查。