泛型对象转换为类型化对象
作者:互联网
public class Generic
{
public object AnonObject {get;set;}
public string ObjectType {get;set;}
}
public class TypedObject
{
public string Name {get;set;}
}
有没有一种方法可以使用ServiceStack序列化或其他库将[Generic]类中的匿名属性AnonObject转换为[TypedObject].
例如理想情况下,我正在寻找一种方法
TypedObject typed = generic.AnonObject.ConvertTo<TypedObject>();
要么
TypedObject typed = generic.AnonObject As TypedOject;
解决方法:
您仍然可以使用ServiceStack的built-in Auto Mapping在匿名和类型化对象之间进行转换,但它们仍必须具有相同的形状,例如:
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
}
var anon = new { Id = 1, Title = "Foo" };
var dto = anon.ConvertTo<Poco>();
dto.PrintDump();
打印已填充的DTO:
{
Id: 1,
Title: Foo
}
ToObjectDictionary和FromObjectDictionary扩展方法在尝试将松散类型的数据结构转换为Typed POCO时也很有用,例如:
var dto = new User
{
FirstName = "First",
LastName = "Last",
Car = new Car { Age = 10, Name = "ZCar" },
};
Dictionary<string,object> map = dtoUser.ToObjectDictionary();
User user = (User)map.FromObjectDictionary(typeof(User));
如果上述选项还不够,另一种可能的解决方案是将该对象序列化/反序列化为JSON,例如:
var json = new { Id = 1, Title = "Foo" }.ToJson();
var dto = json.FromJson<Poco>();
标签:generics,servicestack,c 来源: https://codeday.me/bug/20191119/2037618.html