有没有办法将动态或匿名对象转换为强类型声明的对象? [英] 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(dynamic => new Typed { .... }
类型的东西,或者我可以使用 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;
}
这是你的匿名实例:
// 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 symmetric.
这篇关于有没有办法将动态或匿名对象转换为强类型声明的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!