C# 有没有一种优雅的方法可以将数据复制到结构几乎相同的类型?
假设我已经定义了以下两种类型,第一种用于最初接收JSON,第二种用于表示相同的记录,但可能有空值接收默认值:C# 有没有一种优雅的方法可以将数据复制到结构几乎相同的类型?,c#,.net,types,C#,.net,Types,假设我已经定义了以下两种类型,第一种用于最初接收JSON,第二种用于表示相同的记录,但可能有空值接收默认值: public class JsonInputAsReceived { public string company { get; set; } public string employeeNumber { get; set; } public DateTime? effectiveDate { get; set; } } public class JsonInpu
public class JsonInputAsReceived {
public string company { get; set; }
public string employeeNumber { get; set; }
public DateTime? effectiveDate { get; set; }
}
public class JsonInputWithDefaults {
public string company { get; set; }
public string employeeNumber { get; set; }
public DateTime effectiveDate { get; set; }
}
public static JsonInputWithDefaults setDefaults1(JsonInputAsReceived original) {
return new JsonInputWithDefaults {
company = original.company,
employeeNumber = original.employeeNumber,
effectiveDate = original.effectiveDate ?? DateTime.Today
};
}
下面是应用这些默认值的方法的一个实现:
public class JsonInputAsReceived {
public string company { get; set; }
public string employeeNumber { get; set; }
public DateTime? effectiveDate { get; set; }
}
public class JsonInputWithDefaults {
public string company { get; set; }
public string employeeNumber { get; set; }
public DateTime effectiveDate { get; set; }
}
public static JsonInputWithDefaults setDefaults1(JsonInputAsReceived original) {
return new JsonInputWithDefaults {
company = original.company,
employeeNumber = original.employeeNumber,
effectiveDate = original.effectiveDate ?? DateTime.Today
};
}
这个很好用。但是,如果我的模型类型有很多属性,包括嵌套集合等,那么添加任何“有用”的代码都会带来噪音
有没有优雅的方法来定义两个几乎相同的类型,这样我就可以复制“相同”的部分,而不必手动编写代码?
我不能想出任何不(a)牺牲类型安全(反射、字典)或(b)涉及手动实现几乎复制操作的方法。如果不关心原始数据结构,可以避免编写第二个数据结构。例如,将原始类(JsonInputAsReceived)中的effectiveDate属性重写为 现在可以将对象反序列化为
string json = @"{company:'abc',employeeNumber:'23'}";
var data = JsonConvert.DeserializeObject<JsonInputAsReceived>(json);
string json=@“{公司:'abc',员工编号:'23'}”;
var data=JsonConvert.DeserializeObject(json);
这还可以确保您不必重新创建整个数据查看AutoMapperPlus至AutoMapper。它的内部不再优雅,但您不需要处理messAh。那真是太优雅了!:-)