[C# 4.0] 1. Dynamic
2010-09-30 21:04:24 来源:WEB开发网C# 4.0 引入了 dynamic,让我们可以用类似动态语言的方式对 "未知类型" 对象 "直接" 调用。dynamic 关键字可以在字段、属性、方法参数、方法返回值、委托定义以及本地变量中使用。
class MyClass
{
public dynamic x;
public dynamic Y { get; set; }
public dynamic Test(dynamic o)
{
if (o is int)
return ++o;
else if (o is string)
return o + "...";
else
return null;
}
}
class Program
{
static void Main(string[] args)
{
dynamic o = new MyClass();
o.x = 123;
o.Y = "hello";
Console.WriteLine(o.Test(o.x));
Console.WriteLine(o.Test(o.Y));
}
}
老规矩,看看编译器到底干了什么。
internal class MyClass
{
// Fields
[Dynamic, CompilerGenerated]
private object <Y>k__BackingField;
[Dynamic]
public object x;
// Methods
public MyClass();
[return: Dynamic]
public object Test([Dynamic] object o);
// Properties
[Dynamic]
public object Y { [return: Dynamic] get; [param: Dynamic] set; }
// Nested Types
[CompilerGenerated]
private static class <Test>o__SiteContainer0
{
// Fields
public static CallSite<Func<CallSite, object, object>> <>p__Site1;
public static CallSite<Func<CallSite, object, string, object>> <>p__Site2;
}
}
更多精彩
赞助商链接