using System;
using System.Reflection;
class Program {
class Duck { public string Speak() { return "quack"; } }
// *** 以前 ***
// 过去要通过反射访问编译期未知类型的成员:
// 按名称查找,再 Invoke 并转换结果
static string SpeakOld(object thing) {
MethodInfo method = thing.GetType().GetMethod("Speak");
return (string)method.Invoke(thing, null);
}
// *** 在 4.0 版本中 ***
// dynamic 把整个调用推迟到运行时
static string SpeakNew(dynamic thing) {
return thing.Speak();
}
static void Main() {
Duck duck = new Duck();
Console.WriteLine(SpeakOld(duck));
Console.WriteLine(SpeakNew(duck));
dynamic value = 2;
Console.WriteLine(value + 3); // 5,数字相加
value = "two";
Console.WriteLine(value + "3"); // two3,字符串连接
// 代价:写错的代码不再引发编译器错误
try {
Console.WriteLine(SpeakNew(42));
} catch (Exception e) {
Console.WriteLine(e.GetType().Name); // RuntimeBinderException
}
}
}