Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

.net - Is there a way to convert a dynamic or anonymous object to a strongly typed, declared object?

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?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

Suppose this is your class:

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

Note that this is in theory possible with any serializer/deserializer (XmlSerializer, binary serialization, other json libs), as long as the roundtrip is symmetric.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...