Background: For example, there is a method, there are many parameters, and sometimes only need some of the parameters, sometimes need to use all, or even sometimes do not need, this time to write a long parameter list is not cool, and error-prone, it is necessary to consider C # dynamic type as a parameter. This is especially common when manipulating SQL statements.
The code is as follows:
1 Public Static voidtestdynamic ()2 {3Dynamic d =NewExpandoObject ();4D.name ="SHARPL";5D.age = -;6D.city ="Beijing";7 Dosth (d);8 }9 Ten Public Static voiddosth (Dynamic D1) One { A stringTMP =""; - //to cast a dynamic type to a dictionary type - varKVS = (idictionary<string,Object>) D1; the if(KVS. ContainsKey ("Name")) - { -TMP + ="my name is."+kvs["Name"]; - } + if(KVS. ContainsKey (" Age")) - { +TMP + ="my age is"+ kvs[" Age"]; A } at if(KVS. ContainsKey (" Fun")) - { -TMP + ="my hobby is"+ kvs[" Fun"]; - } - if(KVS. ContainsKey (" City")) - { inTMP + ="my city is"+ kvs[" City"]; - } to Console.WriteLine (TMP); + } -}
As above, we may only enter the name, and sometimes we may need to enter all the information, with the dynamic only one method can be solved without entering a long parameter list.
This situation is often used in database queries or inserts, especially in the insert operation, some tables have many fields, we can not always use each field as a parameter, it is really silly, the above code is just an example.
When to use dynamic in C #