...
This code illustrates some things you can do with duck types that you can't with static types (unless you add in casting, see Casting Types).
| Code Block |
|---|
static1 as int //type is fixed to be an integer dynamic1 as duck //can be anything static1 = 0 dynamic1 = 0 print static1+1 //-> 1 print dynamic1+1 //-> 1 #static1 = "Some string" //error, cannot castconvert string to int dynamic1 = "Some string" //dynamic1 can be "any" type of thing #print static1.ToUpper() //error, static1 is an int, not a string print dynamic1.ToUpper() //-> SOME STRING //You can convert a static type to a dynamic duck type: dynamic2 as duck = static1 print dynamic2 //-> 0 dynamic2 = "Some string" print dynamic2.ToUpper() //-> SOME STRING //or convert a dynamic type to a static type static2 as string = dynamic1 print static2.ToUpper() #static3 as int = dynamic1 //error, cannot cast string to int #print static3 + 2 |
...
A Practical Example: Automating Internet Explorer via COM Interop
| Code Block |
|---|
import System.Threading
def CreateInstance(progid):
type = System.Type.GetTypeFromProgID(progid)
return type()
ie as duck = CreateInstance("InternetExplorer.Application")
ie.Visible = true
ie.Navigate2("http://www.go-mono.com/monologue/")
Thread.Sleep(50ms) while ie.Busy
document = ie.Document
print "$(document.title) is $(document.fileSize) bytes long."
|
...
