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

a 夏天 提交于 2019-12-18 18:37:10

问题


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?


回答1:


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.




回答2:


Your question comes down to the question: can I convert one statically typed variable into another statically typed variable (from different inheritance chains)? and the answer, obviously, is No.

Why does your question come down to the above question?

  • Dynamic type usage compiles into using the Object type with reflection.
  • Your code receives Object in reality, that (in reality) contains value from one particular static type.

So, in fact, your code is dealing with the statically typed value, assigned to the Object, and treated as Dynamic at compile time. Therefore, the only case when you can convert one statically typed value into another [without reflection] is when they are part of the same inheritance chain. Otherwise, you are bound to using reflection explicitly (written by you) or implicitly (written by MS with Dynamic usage).

In other words, the following code will work only if the value assigned to the dynamic is a base or derived type of the Person (invented for the example):

dynamic dPerson = GetDynamicPerson();
Person thePerson = (Person)dPerson;

That's pretty much it.

Fair to mention, you can copy the values byte by byte with unsafe code accessing the memory addresses (like in C++), but that to me is nothing better than reflection.




回答3:


Here we can convert an anonymous object to Dictionary

Dictionary<string, object> dict = 
    obj.GetType()
      .GetProperties()
      .ToDictionary(p => p.Name,  p => p.GetValue(obj, null));

Also you can cast an object using LINQ:

List<MyType> items = anonymousType.Select(t => new MyType(t.Some, t.Other)).ToList();



回答4:


If your object inherits from MarshalByRefObject you can use RealProxy.

Another alternative is to use Reflection but you may be limited by stuff not marked virtual and/or have to use interfaces. You could also have it copy the values, assuming the properties are writable and the empty constructor works for your case.

The actual answer to your question is no, there is no automatic way to treat a dynamic object as a specific type unless it is an instance of that type, nor is there any automatic facility to copy the values from a dynamic/anonymous object into an instance of a named class.

The runtime has no idea what is going on in the constructor or how the class is implemented internally, so any such facility would blow type safety out of the water. The whole point of dynamic is to allow duck typing/runtime dispatch/etc.

edit: If I misunderstood the question let me know, but I am assuming you want to treat a dynamic object as if it were an instance of SomeType.

In my own projects, I've used an Object Mapper class for this where it matches up the property names for writable properties and identical or coercible types so at least I didn't have to write 10,000 lines of boilerplate, though my source wasn't dynamic so I used Reflection.Emit/DynamicMethod to greatly speed it up.



来源:https://stackoverflow.com/questions/17101190/is-there-a-way-to-convert-a-dynamic-or-anonymous-object-to-a-strongly-typed-dec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!