实验发现,dynamic是一个非常有用的东西,但是把它用到什么地方才能把它发挥到极致呢
1.
dynamic yoyo = new ExpandoObject(); //这个对象可以随便添加和移除成员
yoyo.zhu = 1;
yoyo.Increment = new Action(()=>yoyo.zhu++);//这个是函数成员
for (int i = 0; i < 10;i++ )
{
yoyo.Increment();
Console.WriteLine("yoyo.zhu={0}",yoyo.zhu);
}
2.
class Pear
{
public string GetName()
{
return "这是个梨子";
}
}
class Apple
{
public string GetName()
{
return "这是个苹果";
}
}
class tmp
{
static object Get(int i)
{
if(i==1)
{
return new Pear();
}
else
{
return new Apple();
}
}static void Main(string[] args)
{int nDrinkType = Console.Read();
dynamic d = Get(1);
Console.WriteLine(d.GetName());
var dd = Get(1) as Pear;
Console.WriteLine(dd.GetName());
}
}