以前需要将一段json字符串转换为C#对象时,一般都是定义一个与之对应的实体类来接收.这样做有一个很大的缺点,就是当字符串特别长,属性特别多,又有嵌套时,手敲这个实体类就非常痛苦. 比如之前做的一个接收百度七天天气预报的API,层层嵌套,很痛苦. C# 4.0 之后有了动态类型dynamic.用这个东西配合Json.net可以实现不用定义实体类的json转dynamic类型对象. 以下示例需要先引用Newtonsoft.Json.dll public class Person { public…
public class User { //使用省缺参数,一般不需要再为多态做各种静态重载了 public User( string name = "anonym", string type = "user" ) { this.UserName = name; this.UserType = type; } public UserName { private set; get; } public UserType { private set; get; } } Us…
记录一下 引用 using Newtonsoft.Json; using Newtonsoft.Json.Linq; var jsonString = "{\"ApiResources\": [{\"name\": \"name1\",\"Enabled\": true},{\"name\": \"name2\",\"Enabled\": true}]}&q…
原文 automapper如何全局配置map条件过滤null值空值对所有映射起效 我们在使用automapper的时候经常会遇到这样的问题:假设展示给用户的数据我们用UserDto类,User类就是我们的实体类.在给用户编辑的时候,我们可能某些字段在数据库中为Null,这时候需要一些默认值 比如这里UserDto中的BirTime,然后我们有一些人的习惯是在构造函数里面进行赋值 public class User { public int Id { get; set; } public stri…
static void Main(string[] args) { int times = 1000000; string value = "Dynamic VS Reflection"; //reflection 测试开始 TestClass testTypeByReflection = new TestClass(); Stopwatch watch1 = Stopwatch.StartNew(); var property = typeof(TestClass).GetPrope…
class Test : System.Dynamic.DynamicObject { public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { if (map != null) { string name = binder.Name; object value; if (map.TryGetValue(name, out value)) { result = val…