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

前端 未结 4 1050
轻奢々
轻奢々 2020-12-17 07:45

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 obj

4条回答
  •  孤城傲影
    2020-12-17 08:00

    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(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.

提交回复
热议问题