在Web.config保存和读取项目配置(备注)
定义一个备注类:
Imports System.Configuration
Public Class ConfigInfo
Inherits ConfigurationSection
'配置属性UserName映射到配置项属性Name
<ConfigurationProperty("Name")> _
Public Property UserName() As String
Get
Return Me("Name")
End Get
Set(ByVal value As String)
Me("Name") = value
End Set
End Property
'配置属性UserSex映射到配置项属性Sex
<ConfigurationProperty("Sex")> _
Public Property UserSex() As String
Get
Return Me("Sex")
End Get
Set(ByVal value As String)
Me("Sex") = value
End Set
End Property
'配置属性UserQQ映射到配置项属性QQ
<ConfigurationProperty("QQ")> _
Public Property UserQQ() As Integer
Get
Return Me("QQ")
End Get
Set(ByVal value As Integer)
Me("QQ") = value
End Set
End Property
End Class
Public Class ConfigInfo
Inherits ConfigurationSection
'配置属性UserName映射到配置项属性Name
<ConfigurationProperty("Name")> _
Public Property UserName() As String
Get
Return Me("Name")
End Get
Set(ByVal value As String)
Me("Name") = value
End Set
End Property
'配置属性UserSex映射到配置项属性Sex
<ConfigurationProperty("Sex")> _
Public Property UserSex() As String
Get
Return Me("Sex")
End Get
Set(ByVal value As String)
Me("Sex") = value
End Set
End Property
'配置属性UserQQ映射到配置项属性QQ
<ConfigurationProperty("QQ")> _
Public Property UserQQ() As Integer
Get
Return Me("QQ")
End Get
Set(ByVal value As Integer)
Me("QQ") = value
End Set
End Property
End Class
配置Web.Config文件
<configuration>
<configSections>
<section name="MyConfigSection" type="WebApplication1.ConfigInfo"/>
</configSections>
<MyConfigSection Name="没剑" QQ="12101948" Sex="男"/>
...
<configSections>
<section name="MyConfigSection" type="WebApplication1.ConfigInfo"/>
</configSections>
<MyConfigSection Name="没剑" QQ="12101948" Sex="男"/>
...
好了,配置好web.config我们就开始动手把它读出来吧,代码如下:
Dim ConfigInfo As ConfigInfo = TryCast(ConfigurationManager.GetSection("MyConfigSection"), ConfigInfo) '将读取来的配置属性用TryCast转换成类型:ConfigInfo(TryCast的用法,在后面有附)
Response.Write(ConfigInfo.UserName & "<br>")
Response.Write(ConfigInfo.UserSex & "<br>")
Response.Write(ConfigInfo.UserQQ & "<br>")
Response.Write(ConfigInfo.UserName & "<br>")
Response.Write(ConfigInfo.UserSex & "<br>")
Response.Write(ConfigInfo.UserQQ & "<br>")
TryCast:引入不引发异常的类型转换操作。
如果尝试转换失败,则 CType 和 DirectCast 都会引发 InvalidCastException 错误。这将给应用程序的性能造成负面影响。TryCast 返回 Nothing (Visual Basic),因此只需测试返回的结果是否为 Nothing,而无需处理可能产生的异常。
使用 TryCast 关键字的方法与使用 CType 函数和 DirectCast 关键字的方法相同。提供一个表达式作为第一个参数,并提供要将其转换成的类型作为第二个参数。TryCast 仅适用于引用类型,如类和接口。它要求这两种类型之间的关系为继承或实现。这意味着一个类型必须继承自或实现另一个类型。
错误和失败
如果 TryCast 检测到不存在任何继承或实现关系,它将生成一个编译器错误。但是不出现编译器错误并不能保证转换成功。如果需要的转换为收缩转换,它可能在运行时失败。如果发生这种情况,TryCast 返回 Nothing (Visual Basic)。
---
TryCast是VB特有的,在C#中TryCast等同as运算符。