The topic starts with today's Terrylee code about MVC:
protected void Application_Start()
{
RouteTable.Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
Note that new {controller = "Home", action = "Index", id = ""} parameter, which is the anonymous type introduced by c#3.0. Because an anonymous type is a type that is automatically generated by the compiler, Maproute does not know its exact type at compile time, but instead parses its properties at run time to obtain information by reflection. This approach is elegant and concise in syntax, which is called mutation Assignment (mutantic assignment).
Normally we need several assignment statements to modify the properties of a Form object:
form.Text = “Hello World”;
form.Top = 100;
form.Left = 200;
If C # supports mutation replication, it can be done in a sentence like this:
form := new {Text = “Hello World”, Top = 100, Left = 200};
Is this going to be simple and elegant? Unfortunately, C # has no support for mutation assignment operators: =. On a larger level, it is a pity that the C # operator overload still has many limitations, and there is no syntax macro like the Boo language support. Expect in the future C #, we can make direct custom language syntax, make the code more elegant and concise. But now we're not going to do it. Second, we can only try to simulate the mutation assignment function in c#3.0 using the extension method:
public static class Mutant
{
public static void MAssign(this object target, object source)
{
foreach (PropertyInfo pi1 in source.GetType ().GetProperties())
{
if (!pi1.CanRead) continue;
PropertyInfo pi2 = target.GetType ().GetProperty(pi1.Name, pi1.PropertyType);
if (null == pi2 || !pi2.CanWrite) continue;
pi2.SetValue(target, pi1.GetValue(source, null), null);
}
}
}
The above defines the Massign extension method for the object class, and gets and sets the property value to simulate the mutation assignment by reflection. In this way, we can assign a mutation to any object:
Form. Massign (New {Text = ' Hello world ', top = +, left = 200});