有什么方法可以像ExpandoObject
在 VB.NET 中一样使用 4.0 框架中的新动态功能而无需设置Option Strict Off
?在 C# 中,只有明确声明为dynamic
. 但是对于 VB,我发现使用这些功能的唯一方法是使用Option Strict Off
从一开始就存在于 VB.NET 中的旧技巧。如果没有 Option Strict,文件中的所有内容都会被模糊类型污染,如下所示:
Option Explicit On
Option Strict Off
Option Infer On
Partial Public Class ClassX
Public Sub TestDynamic()
Dim dyn As Object = New System.Dynamic.ExpandoObject()
Dim a As String = 1 ''# Ew!
Dim obj As Object = "999"
dyn.Str = a ''# a is a string, remember? Even though it has a number
''# dyn.Str = 1 : Type = System.String
Console.WriteLine("dyn.Str = {0} : Type = {1}", dyn.Str, dyn.Str.GetType().ToString())
dyn.Num = 123
''# dyn.Num = 123 : Type = System.Int32
Console.WriteLine("dyn.Num = {0} : Type = {1}", dyn.Num, dyn.Num.GetType().ToString())
dyn.Dbl = obj / 9
''# dyn.Dbl = 111 : Type = System.Double
Console.WriteLine("dyn.Dbl = {0} : Type = {1}", dyn.Dbl, dyn.Dbl.GetType().ToString())
dyn.Obj = obj
''# dyn.Obj = 999 : Type = System.String
Console.WriteLine("dyn.Obj = {0} : Type = {1}", dyn.Obj, dyn.Obj.GetType().ToString())
dyn.Dte = #5/5/1955#
''# dyn.Dte = 7/7/1977 12:00:00 AM : Type = System.DateTime
Console.WriteLine("dyn.Dte = {0} : Type = {1}", dyn.Dte, dyn.Dte.GetType().ToString())
AmICalled(dyn.Num)
AmICalled(dyn.Obj)
AmICalled(dyn.Str)
AmICalled(dyn.Dbl)
Try
AmICalled(dyn.Dte)
Catch
Console.WriteLine("Dates don't convert to ints I guess... but we don't know that 'till runtime")
End Try
Console.WriteLine(dyn.Num + dyn.Str) ' 124!?
Console.WriteLine(dyn.Num & dyn.Str) ' 1231!?
End Sub
Private Sub AmICalled(ByVal i As Integer)
Console.WriteLine("AmICalled was called with: " & i)
End Sub
End Class
这真的正确吗?而且,如果是这样,那么仍然使用诸如此类的东西ExpandoObject
并减轻失去所有类型安全性的风险的最佳方法是什么?部分课程?还是在这种情况下我不应该那么担心类型安全?