Home >Backend Development >C#.Net Tutorial >Detailed explanation of the creation of c# dynamic types and dynamic objects, merging 2 objects, and map example code
The following editor will bring you an articlec#Dynamic types, the creation of dynamic objects, merging 2 objects, and map instances. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.
We often encounter situations like this. We need to process the data when responding to the data requested by the client. For example, the data in the database is of type int, which may mean An enumeration, or other logical meaning (the design of the database may be from the perspective of data security, storage capacity, etc.), but its specific meaning needs to be displayed on the client.
At this time, our processing method is generally 2. If the logic is not complicated and single, the data source can be processed by directly modifying the SQL statement. At this time, there is no need to process anything in the code.
But if the logic is slightly complex or the judgment situation has many branches, we have to deal with it from the code perspective. A single object is okay, but if there are multiple objects, such as a list8742468051c85b06f0a0af9e3e506b5c, then you have to loop to perform XXX on the fields of a certain object.
Then this is derived, which is DTO, the intermediate object of Arg. Of course, I personally like this design, but sometimes I am lazy and don’t want to write it (most of the time I write code directly to generate (mass production of the machine), for example, when testing, when taking on private work, when demonstrating, just to quickly present the desired effect, you are too lazy to bother. Yes, you will say that there are not many map libraries on the market. For example, there are many ways to rewrite dynamic features such as automap, tinymap, and even json.net, but I don’t think it’s worthwhile to use a big wheel to do such a small thing. And the wheel gets bigger and bigger, the more things it has to do, and I don’t want to make it so complicated, well, that’s it, I wrote this.
The specific code is posted below. If you understand it, you will easily expand or modify it to 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[]>(); private 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> /// 支持动态输出的对象接口 /// </summary> public interface IInjectClass { } /// <summary> /// 动态输出时忽略此标记的属性 /// </summary> public class IngorePropertyAttribute : Attribute { }
Let’s test one below:
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 + "(改变了哦)"; }); var json = Tools.JsonUtils.JsonSerializer(tt); json = json + "<br /><br />" + Tools.JsonUtils.JsonSerializer(ToDynamicResult<kk>( new kk { aa = "test", bb = 789, cc = true, dd = DateTime.Now.AddDays(2) }, null)); Response.Write(json);
You can reconstruct the properties with parameters or modify the injectAct object to suit Write a test below your
, change it to expressiontree is the best, first put a 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 static readonly ConcurrentDictionary<RuntimeTypeHandle, PropertyInfo[]> DynamicObjectProperties = new ConcurrentDictionary<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> /// 单个对象映射 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="source">实例</param> /// <param name="injectAct">map方法集</param> /// <returns>映射后的动态对象</returns> public static IDictionary<string, Object> DynamicResult<T>(T source, params MapCondition[] injectAct)//where T : ICustomMap { var queryPts = GetObjectProperties<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; //原来是属性名 var _value = p.GetValue(source, null); //原来的属性值 object _resultvalue = _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> /// 合并2个对象 /// </summary> /// <typeparam name="TSource">对象1类型</typeparam> /// <typeparam name="TTarget">对象2类型</typeparam> /// <param name="s">对象1实例</param> /// <param name="t">对象2实例</param> /// <returns>合并后的动态对象</returns> public static IDictionary<string, Object> MergerObject<TSource, TTarget>(TSource s, TTarget t) { var targetPts = GetObjectProperties<TSource>(); 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> /// 合并2个对象 /// </summary> /// <typeparam name="TSource">对象1类型</typeparam> /// <typeparam name="TTarget">对象2类型</typeparam> /// <param name="s">对象1实例</param> /// <param name="t">对象2实例</param> /// <returns>合并后的动态对象</returns> public static List<IDictionary<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), true); 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; } } }
and 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(result); 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.JsonSerializer(result); Response.Write(json);
The output is as follows:
{ "key": "aaa", "value": "111", "p": "jon test" }
The above is the detailed content of Detailed explanation of the creation of c# dynamic types and dynamic objects, merging 2 objects, and map example code. For more information, please follow other related articles on the PHP Chinese website!