JavaScript is a dynamic language that can dynamically add properties and methods to objects, which is very convenient. Is there a way for C # to have the ability to dynamically add properties and methods, programming like JavaScript? Here is a good framework claysharp can achieve the above functions.
After building a new object with Claysharp, the following code can be used to dynamically add properties using new:
Here is a detailed step:
1 Create a new console program and introduce the class library
You must introduce the Claysharp namespace:
1 // Claysharp enables C # to have dynamic programming capabilities for JavaScript 2 using Claysharp;
Create a new object with Clayfactory, and you can create a dynamic object at random after the new object:
1 DynamicNew =Newclayfactory ();2 varperson =New.person ();3person["FirstName"] ="Louis";4person["LastName"] ="Dejardin";5Person. Age = -;
Object properties can be created by using [] or. You can also create a dynamic method:
1 varMan =New.jackwang ();2Man. FirstName ="Jack";3Man. LastName ="Wang";4Man. Sayfullname =Newfunc<string,string> (x = man. FirstName + man. LastName +x);5Output6Console.WriteLine (man. Sayfullname () ("here!"));
Claysharp also supports the creation and assignment of attributes using concatenating methods:
1 varPeoples =New.array (2New.person (). FirstName ("Jack"). LastName ("Wang"),3New.person (). FirstName ("Jack"). LastName ("CUMT")4 );5Console.WriteLine ("{0}","----------Claysharp-------------");6 foreach(varPinchpeoples)7 {8Console.WriteLine ("{0} {1}", P.firstname, p.lastname);9}
In fact, in the higher version of C #, there are built-in object ExpandoObject also have similar functions, but the function is slightly weaker than Claysharp:
1Console.WriteLine ("{0}","-----System.Dynamic.ExpandoObject----");2 //---------------ExpandoObject---------------------------------------------3 DynamicExpobject =NewSystem.Dynamic.ExpandoObject ();4Expobject.nickname ="Jack";5 //expobject["nickname"] = "Jack";//Error6Expobject.realname ="Wang";7Console.WriteLine ("{0} {1}", Expobject.nickname, expobject.realname);8Console.ReadLine ();
How to make C # programming like JavaScript