将泛型对象转换为类型化对象

本文关键字:对象 类型化 转换 泛型 | 更新日期: 2023-09-27 18:16:15

public class Generic
{
   public object AnonObject {get;set;}
   public string ObjectType {get;set;}
}

public class TypedObject
{
   public string Name {get;set;}
}

是否有办法使用ServiceStack serialization或其他库将类[Generic]中的匿名属性AnonObject转换为[TypedObject]。

。理想情况下,我正在寻找一个方法

TypedObject typed = generic.AnonObject.ConvertTo<TypedObject>();   

TypedObject typed = generic.AnonObject As TypedOject;

将泛型对象转换为类型化对象

您尝试过ServiceStack的内置自动映射方法吗?

TypedObject typed = generic.AnonObject.To<TypedObject>();
TypedObject typed = generic.AnonObject.TranslateTo<TypedObject>();
TypedObject typed = generic.AnonObject.ConvertTo<TypedObject>();
TypedObject typed  = new TypedObject();
typed.PopulateWith(generic.AnonObject);

你仍然可以使用ServiceStack内置的自动映射在匿名对象和类型对象之间进行转换,但它们仍然必须具有相同的形状,例如:

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
}

ToObjectDictionaryFromObjectDictionary扩展方法在将松散类型数据结构转换为类型化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>();