A detailed description of C # Dynamic types and dynamic object creation, merging 2 objects, map instance code

Source: Internet
Author: User
The following small series for everyone to bring a C # dynamic type, and the creation of dynamic objects, merging 2 objects, map instances. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

This is often the case when we respond to the data requested by the client, we need to process the data, such as the data in the database is an int, it may represent an enumeration, or other logical meaning (the database design may be from the data security, storage, etc.), But the client needs to be the exact meaning of its display.

This time we are generally handled in 2, if the logic is not complex, and a single word, directly modify the SQL statement can handle the data source, this time the code does not need to deal with anything.

But if there are many branches to the logic complex or the judging situation, we have to deal with it from the point of view of code. A single object is good, multiple objects such as a list<t>, it is necessary to loop the field of an object xxx.

Then derived from this appeared Dto,arg intermediate object, of course, I personally like this design, but some time will be lazy don't want to write (most of the case I directly write code generator mass production), such as in the test, in the time of the reverse telecommuting, in the presentation, only to quickly present the desired effect Do not bother to chip, yes, you will say there are not many map libraries in the market, such as Automap,tinymap, and even json.net inside the dynamic characteristics of rewriting, method of course a lot of, but with a big wheel to work on such a trivial matter, I feel that can not be scratched. And the wheels are getting bigger. The more things it's going to do, the more I don't want to be complicated, well, that's it, write a.

Specific code to paste below, if you see, it will be convenient to expand or modify the effect you want.

Using system.dynamic;using system.reflection;using system.collections.concurrent;private static readonly Concurrentdictionary<runtimetypehandle, propertyinfo[]> dynamicobjectproperties = new ConcurrentDictionary <runtimetypehandle, propertyinfo[]> ();p rivate idictionary<string, object> ToDynamicResult<T> (T  Classobj, Func<string, object, object> injectact) where T:iinjectclass, new () {var type = typeof (T); var key = type.  Typehandle;  var dynamicresult = new ExpandoObject () as idictionary<string, object>;  propertyinfo[] querypts = null;  Dynamicobjectproperties.trygetvalue (key, out querypts); if (querypts = = null) {querypts = type.    GetProperties ();  Dynamicobjectproperties.tryadd (key, querypts);    } foreach (Var p in querypts) {var attributes = P.getcustomattributes (typeof (Ingorepropertyattribute), true); var columnmapping = attributes.    FirstOrDefault ();    if (columnmapping! = null) continue;    var _name = p.name; var _value = P.    GetValue (classobj, NULL);    Object _tempvalue = _value;    if (injectact! = null) _tempvalue = Injectact.invoke (_name, _value);     var value = Convert.changetype (value,typeof (string));  Dynamicresult.add (P.name, _tempvalue); } return Dynamicresult;} <summary>///object interface for dynamic output///</summary>public interface iinjectclass{}///<summary>/// Ignore properties of this tag when dynamic output//</summary>public class ingorepropertyattribute:attribute{}

Below we test one:

public class Kk:iinjectclass {public  string AA {get; set;}  public int BB {get; set;}  [Ingoreproperty]  public bool cc {get; set;}  Public DateTime dd {get; set;}}  KK ist = new KK (); ist.aa = "AAA"; ist.bb = 123;ist.cc = FALSE;IST.DD = Datetime.now;var TT = todynamicresult<kk> (ist, (k, v) =>{  if (k! = "AA") return V;  Return v + "(changed OH)";}); var json = Tools.JsonUtils.JsonSerializer (TT), JSON = JSON + "<br/><br/>" + Tools.JsonUtils.JsonSerializer (T Odynamicresult<kk> (    new KK    {      AA = "Test",      bb = 789,      cc = true,      dd = DateTime.Now.AddDays (2)    }, null)); Response.Write (JSON);

You can reconstruct the attributes with parameters or modify the Injectact object to fit your own

Write a test below, change to the expression tree the best, the first code

Using system;using system.linq;using system.dynamic;using system.reflection;using system.linq.expressions;using System.collections.generic;using system.collections.concurrent;namespace tools{public class Class2Map {private stat IC readonly concurrentdictionary<runtimetypehandle, propertyinfo[]> dynamicobjectproperties = new ConcurrentDic    Tionary<runtimetypehandle, propertyinfo[]> ();      private static propertyinfo[] getobjectproperties<t> () {var type = typeof (T); var key = type.      Typehandle;      propertyinfo[] querypts = null;      Dynamicobjectproperties.trygetvalue (key, out querypts); if (querypts = = null) {querypts = type.        GetProperties ();      Dynamicobjectproperties.tryadd (key, querypts);    } return querypts; }///<summary>///single object mapping///</summary>//<typeparam name= "T" > Type </typeparam>// /<param name= "source" > Instance </param>//<param name= "Injectact" >mAP method Set </param>///<returns> mapped dynamic objects </returns> public static idictionary<string, object> Dyna Micresult<t> (T source, params mapcondition[] injectact)//where T:icustommap {var querypts = Getobjectprop      Erties<t> ();      var dynamicresult = new ExpandoObject () as idictionary<string, object>;        foreach (var p in querypts) {var attributes = P.getcustomattributes (typeof (Ingoreproperty), true); if (attributes.        FirstOrDefault () = null) continue;           var _name = p.name; The original is the attribute name var _value = p.getvalue (source, NULL);      The original attribute value of object _resultvalue = _value;          The final mapped value if (injectact! = null) {string _tempname = null;          var condition = injectact.firstordefault (x = x.orginal = = _name);            if (Checkchangeinfo (condition, out _tempname)) {_resultvalue = Condition.fn.Invoke (_value); Dynamicresult.add (_tempname, _name, _resUltvalue);          Continue         }}//var value = Convert.changetype (value,typeof (string));      Dynamicresult.add (_name, _resultvalue);    } return Dynamicresult; }///<summary>///Merge 2 objects///</summary>//<typeparam name= "TSource" > object 1 Type </typeparam&    Gt <typeparam name= "Ttarget" > object 2 Type </typeparam>//<param name= "S" > Object 1 instance </param>//<pa  Ram Name= "T" > object 2 instances </param>//<returns> merged dynamic Objects </returns> public static idictionary<string, Object> Mergerobject<tsource, ttarget> (TSource s, Ttarget t) {var targetpts = Getobjectproperties<ts      Ource> ();      propertyinfo[] mergerpts = null;      var _type = T.gettype (); Mergerpts = _type. Name.contains ("<>")? _type.      GetProperties (): getobjectproperties<ttarget> ();      var dynamicresult = new ExpandoObject () as idictionary<string, object>; foreach (Var p in Targetpts) {var attributes = P.getcustomattributes (typeof (Ingoreproperty), true); if (attributes.        FirstOrDefault () = null) continue;      Dynamicresult.add (P.name, p.getvalue (S, null));        } foreach (Var p in mergerpts) {var attributes = P.getcustomattributes (typeof (Ingoreproperty), true); if (attributes.        FirstOrDefault () = null) continue;      Dynamicresult.add (P.name, p.getvalue (t, null));    } return Dynamicresult; }///<summary>///Merge 2 objects///</summary>//<typeparam name= "TSource" > object 1 Type </typeparam&    Gt <typeparam name= "Ttarget" > object 2 Type </typeparam>//<param name= "S" > Object 1 instance </param>//<pa Ram Name= "T" > object 2 instance </param>//<returns> merged dynamic object </returns> public static list<idictionary&lt  ; string, object>> Mergerlistobject<tsource, ttarget> (list<tsource> s, Ttarget t) {var targetPts = Getobjectproperties<tSource> ();      propertyinfo[] mergerpts = null;      var _type = T.gettype (); Mergerpts = _type. Name.contains ("<>")? _type.      GetProperties (): getobjectproperties<ttarget> ();      var result = new list<idictionary<string, object>> ();        S.foreach (x = = {var Dynamicresult = new ExpandoObject () as idictionary<string, object>;          foreach (var p in targetpts) {var attributes = P.getcustomattributes (typeof (Ingoreproperty), true); if (attributes.          FirstOrDefault () = null) continue;        Dynamicresult.add (P.name, p.getvalue (x, null)); } foreach (Var p in mergerpts) {var attributes = P.getcustomattributes (typeof (Ingoreproperty), Tru          e); if (attributes.          FirstOrDefault () = null) continue;        Dynamicresult.add (P.name, p.getvalue (t, null)); } result.      ADD (Dynamicresult);      });    return result; } private static bool Checkchangeinfo (mapcondition condition, out string name) {name = NULL; BOOL result = condition! = NULL && CONDITION.FN! = null &&!string. Isnullorwhitespace (condition.orginal);//&&//!string. Isnullorwhitespace (condition.      NewName); if (result) {var temp = condition.        NewName; Name = (String. Isnullorwhitespace (temp) | | Temp. Trim (). Length = = 0)?      Null:temp;    } return result; }  }}

Test it:

list<keyvalue> KK = new List<keyvalue> {   new keyvalue{key= "AAA", value= "111"},  new keyvalue{key= " BBB ", value=" 222 "},  new keyvalue{key=" CCC ", value=" 333 "},  new keyvalue{key=" ddd ", value=" 444 "},};var result = Class2map.mergerlistobject<keyvalue, Dynamic> (KK, new {p = "Jon Test"}); var json = Jsonutils.jsonserializer (resul T); Response.Write (JSON);

The output is as follows:

[{"Key": "AAA", "Value": "111", "P": "Jon Test"},{"key": "BBB", "Value": "222", "P": "Jon Test"},{"key": "CCC", "value": "333 "," P ":" Jon Test "},{" key ":" DDD "," Value ":" 444 "," P ":" Jon Test "}]var result = Class2map.mergerobject<keyvalue, Dynamic> (        new KeyValue {key = "AAA", value = "111"},        new {p = "Jon Test"}      ); var json = Jsonutils.jsonse Rializer (result); Response.Write (JSON);

The output is as follows:

{"key": "AAA", "Value": "111", "P": "Jon Test"} 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.