The theme of # 4.0 is Dynamic programming (programming). Although C # is still a static language, the meaning of the object begins to become more and more "dynamic". Their structure and behavior cannot be captured by a static type, or at least the compiler cannot know the structure and behavior of the object when compiling the program.
C # introduces a new static type of "dynamic", and when you have an object of type dynamic, what you "do to it" will only be parsed at run time. Imagine that we have these two classes that represent two kinds of drinks:
public class Coffee
{public string GetName ()
{
Return "you selected Maxwell coffee.";
}
}
public class Juice
{
public string GetName ()
{
Return "you selected orange juice.";
}
}
Now we can use the dynamic type to represent the two drinks. We write a function getdrink () that returns different objects depending on the user's choice.
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 ());
}
The C # compiler allows you to invoke any method through a dynamic object, even if the method does not exist at all, and the compiler will not compile the error when compiling. It only checks the actual type of the object when it is running, and checks what getname () means on it. Dynamic typing will allow C # to represent the following objects in a more uniform and convenient form:
Objects from a dynamic programming language-such as Python or ruby--
COM objects accessed through IDispatch
Accessed by reflection in general. NET Type
Objects that have changed structures-such as HTML DOM objects
When we get an object of a dynamic type, whether it comes from COM or IronPython, HTML dom, or reflection, it only needs to be manipulated, and the Dynamic Language runtime (DLR) helps us to point out specific objects and the specific meanings of those operations. This will bring great flexibility to our development and can greatly streamline our code.
-
Top
-
0
-
Step
Dynamic typing and dynamic programming in C # 4.0