有什么办法可以使用4.0框架中的新动态功能,如VB.NET中的ExpandoObject,而不设置Option Strict Off?使用C#,您只能使用特定声明为动态变量的类型安全.但是使用VB,我发现使用这些功能的唯一方法是从一开始就在VB.NET中的旧的Option Strict Off技巧.没有选项严格,文件中的所有内容都会受到模糊类型的污染:
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这样的东西,并减轻丢失所有类型安全的风险?部分班?或者在这种情况下,我该不该担心类型安全吗?
看来你不必不必选择严格关闭.
我会研究一些.
原文链接:https://www.f2er.com/vb/255721.html我会研究一些.
编辑
经过ExpandoObject上的一些文档,它似乎在COM和Office Interop的C#中使用.传统上,在VB.NET中,Object被用于这样的目的,这将需要你关闭Option Strict.
为了回答你的问题,这意味着你可以通过使用对象类型而不是ExpandoObject来使用VB.NET中的动态类型[如果VB.NET中存在这样的类型],设置Option Infer On和Option Strict On或Off.
您还可以考虑使用部分类来将非选项严格代码本地化为特定文件.
建议阅读
> Dynamic Type in C#,Equivalent in VB
> Using Type Dynamic (C# Programming Guide)