how to convert anonymous type to known type

♀尐吖头ヾ 提交于 2019-12-23 19:09:11

问题


I have an anonymous type variable. This variable is get from another function, we couldn't change it.

// var a {property1 = "abc"; property2 = "def"}

I have a class:

class Myclass{
   string property1;
   string property2;
}

How to convert variable a to Myclass type. I tried

Myclass b = (Myclass)a; 

but it doesn't work.

If I initialize:

Myclass b = new Myclass{
  property1 = a.property1,
  property2 = a.property2,
} 

it is working, but it take a lot of code because MyClass has many properties

Can anyone help me? Thanks for any answer.


回答1:


You can't use casting here, because neither you anonymous type inherited from MyClass nor you have explicit type conversion operator defined for these types.

You can use AutoMapper (available from NuGet) to dynamically map between anonymous type and your class

var a = new {property1 = "abc", property2 = "def"};
Myclass b = Mapper.DynamicMap<Myclass>(a);

It maps properties of anonymous object to properties of destination type by name:



来源:https://stackoverflow.com/questions/24257872/how-to-convert-anonymous-type-to-known-type

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