服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - c#动态类型,及动态对象的创建,合并2个对象,map实例

c#动态类型,及动态对象的创建,合并2个对象,map实例

2021-12-24 13:50C#教程网 C#

下面小编就为大家带来一篇c#动态类型,及动态对象的创建,合并2个对象,map实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

经常会遇到这样的情况,我们在响应客户端请求的数据的时候需要对数据进行处理,比如数据库中的数据是int型,它可能表示某个枚举,或者其它的逻辑意义(数据库这样的设计可能是从数据安全性、存储量上等角度考虑),但是客户端显示的时候需要是它具体的意义。

这个时候我们的处理方式一般都是2中的,如果逻辑不复杂,且单一的话,直接修改sql语句就能处理好数据源,这个时候代码里面不需要处理什么。

但是如果逻辑复稍许复杂或者判断的情况有很多分支,我们不得不从代码角度来处理了。单个对象还好,多个对象比如是个list<T>,那就要循环对某个对象的字段进行XXX了。

进而衍生出了这就出现了DTO,Arg的中间对象,当然,我个人是很喜欢这样的设计的,但是某些时候也会偷懒不想写(多半情况我直接写代码生器批量生产),比如在测试的时候,在接私活的时候,在演示的时候,只为快速呈现想要的效果 都懒得去屑,是的,你会说市面上不是有很多的map库,比如automap,tinymap,甚至json.net里面的动态特性重写,方法当然很多,但用一个大轮子来费力搞这么个小事,我觉得划不来。且轮子越来越大它要干的事越多,我可不想搞的那么复杂,嗯,就是这样,写了个。

具体的代码贴到下面,如果看明白,会很方便的扩展了或修改成自己想要的效果。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
{
}

下面我们测试一个:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);

您可以重新构造带参数的特性或者修改injectAct对象,改成适合自己的

下面写个测试,改成表达式树最好了,先上个码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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;
    }
  }
}

测试一下:

?
1
2
3
4
5
6
7
8
9
10
11
12
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);

输出如下:

?
1
2
3
4
5
6
7
8
9
[{"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);

输出如下:

?
1
{ "key": "aaa", "value": "111", "p": "jon test" }

以上这篇c#动态类型,及动态对象的创建,合并2个对象,map实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10