将通用对象转换为类型化对象

时间:2015-10-06 06:47:35

标签: c# generics servicestack

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


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

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

e.g。理想情况下,我正在寻找一种方法

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

TypedObject typed = generic.AnonObject As TypedOject;

2 个答案:

答案 0 :(得分:2)

您是否尝试过ServiceStack的built-in Auto-Mapping方法?

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);

答案 1 :(得分:1)

你可以使用仍然使用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
}

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>();