VB的日益动态化

Ruby和其他动态语言里有个东西叫Duck Typing,按Dave Thomas的话来说,if an object walks like a duck and talks like a duck, then it must be a duck (如果一个对象走起路来象鸭子,叫起来也象鸭子,那么它一定是只鸭子!)

譬如,Ruby里可以这么做

class Duck
 def Quack
   puts “I am a duck, so I quack”
 end
end

class Pig
 def Quack
   puts “I am a pig, I don’t quack, but I am faking…”
 end
end

animals = [Duck.new, Pig.new]
animals.each {|animal| animal.Quack}

即使是只猪,只要它能Quack,在这里它就是只鸭。在Ruby里,the type of an object is defined by what that object can do。

VB里也有这样的动态机制,譬如,通过后期绑定,你可以这么做

Option Explicit On
Option Strict Off ‘this is important

Imports System

Class Duck
 Sub Quack()
   Console.WriteLine(“I am a duck, so I quack”)
 End Sub
End Class

Class Pig
 Sub Quack()
   Console.WriteLine(“I am a pig, I don’t quack, but I am faking…”)
 End Sub
End class

Class TestDuck
  Shared Sub Main
 dim animals() = {New Duck, New Pig}
 for each animal in animals
  animal.Quack()
 next
  End Sub
End Class

还能以动态接口的方式做,

Dynamic Interface IQuack
  Sub Quack
End Interface

dim animals() = {New Duck, New Pig}
for each animal in animals
 dim a as IQuack = animal
 a.Quack()
next

还引进了动态Dynamic Identifiers的概念,文档声称你可以这么做

dim t = Type.GetType(“Duck”)
dim o  = New(t)(new object(){})
o.(“Quack”)() 

可惜编译时出错,

C:\Program Files\VB LINQ Preview\Bin\TestDuck.vb(41) : error BC30182: Type expected.
dim o  = New(t)(new object(){}) 
              
但这么做是可以的,

dim t = Type.GetType(“Duck”)
dim o = Activator.CreateInstance(t, new object(){})
o.(“Quack”)()   ‘通过字符串来调用方法

文档最后说,
“…….This makes Visual Basic 9.0 an excellent choice for modern Agile and test-driven development methodologies.”

这样下去,VB也许会成为大家最喜欢的语言的,