【IT168 技术文档】C# 4.0的主题就是动态编程(Dynamic Programming)。虽然C#仍然是一种静态语言,但是对象的意义开始变得越来越“动态”。它们的结构和行为无法通过静态类型来捕获,或者至少编译器在编译程序时无法得知对象的结构和行为。
C#引入了一种新的静态类型”dynamic”,当你拥有了一个dynamic类型的对象后,你“对它做的事情”只会在运行时进行解析。设想我们拥有这样两个类,分别表示两种饮料:
public class Coffee
{ public string GetName()
{
return "You selected Maxwell coffee.";
}
}
public class Juice
{
public string GetName()
{
return "You selected orange juice.";
}
}
{ public string GetName()
{
return "You selected Maxwell coffee.";
}
}
public class Juice
{
public string GetName()
{
return "You selected orange juice.";
}
}
现在,我们就可以用dynamic类型来表示这两种饮料。我们写一个函数GetDrink(),根据用户不同的选择返回不同的对象。
static private Object GetDrink(int i)
{
if (i == 1)
{
return new Juice();
}
else
// default
{
return new Coffee();
}
}
static void Main(string[] args)
{Console.WriteLine("Please Select Your Drink: 1 -- Juice; 2 -- Coffee");
int nDrinkType = Console.Read();
dynamic drink = GetDrink( nDrinkType );
Console.WriteLine( drink.GetName() );
}
{
if (i == 1)
{
return new Juice();
}
else
// default
{
return new Coffee();
}
}
static void Main(string[] args)
{Console.WriteLine("Please Select Your Drink: 1 -- Juice; 2 -- Coffee");
int nDrinkType = Console.Read();
dynamic drink = GetDrink( nDrinkType );
Console.WriteLine( drink.GetName() );
}