问题
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