有没有一种方法,以动态或匿名对象转换为强类型,声明的对象? [英] Is there a way to convert a dynamic or anonymous object to a strongly typed, declared object?
问题描述
如果我有一个动态的对象,或者匿名对象对于这个问题,它的结构完全匹配,一个强类型的对象,是有一个.NET方法从动态对象建立一个类型的对象?
If I have a dynamic object, or anonymous object for that matter, whose structure exactly matches that of a strongly typed object, is there a .NET method to build a typed object from the dynamic object?
我知道我可以使用LINQ dynamicList.Select(动态=>新建类型化{......}
键入的东西,或者我可以使用Automapper,但我敢不知道是否有不是特别打造了这一点?
I know I can use a LINQ dynamicList.Select(dynamic => new Typed { .... }
type thing, or I can use Automapper, but I'm wondering if there is not something specially built for this?
推荐答案
您可以序列为中间格式,只是为了反序列化后的权利。这不是最优雅的或有效的方式,但它可能让你的工作做好:
You could serialize to an intermediate format, just to deserialize it right thereafter. It's not the most elegant or efficient way, but it might get your job done:
假如这是你的类:
// Typed definition
class C
{
public string A;
public int B;
}
这是匿名的实例:
And this is your anonymous instance:
// Untyped instance
var anonymous = new {
A = "Some text",
B = 666
};
您可以序列化匿名版本的中间格式,然后再反序列化到一个类型版本。
You can serialize the anonymous version to an intermediate format and then deserialize it again to a typed version.
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(anonymous);
var c = serializer.Deserialize<C>(json);
请注意,这是在理论上可能与任何串行器/解串器(的 XmlSerializer的,二进制序列化,其他的JSON库),只要往返是同步的。
Note that this is in theory possible with any serializer/deserializer (XmlSerializer, binary serialization, other json libs), as long as the roundtrip is synchronous.
这篇关于有没有一种方法,以动态或匿名对象转换为强类型,声明的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!