问题描述
我有一个匿名类型变量.此变量是从另一个函数获取的,我们无法更改.
I have an anonymous type variable. This variable is get from another function, we couldn't change it.
// var a {property1 = "abc"; property2 = "def"}
我有一堂课
class Myclass{
string property1;
string property2;
}
如何将变量a
转换为Myclass
类型.我尝试过
How to convert variable a
to Myclass
type. I tried
Myclass b = (Myclass)a;
但它不起作用.
如果我初始化:
Myclass b = new Myclass{
property1 = a.property1,
property2 = a.property2,
}
它可以工作,但是需要很多代码,因为MyClass
具有许多属性
it is working, but it take a lot of code because MyClass
has many properties
有人可以帮助我吗?感谢您的回答.
Can anyone help me? Thanks for any answer.
推荐答案
您不能在此处使用强制转换,因为您既没有继承自MyClass
的匿名类型,也没有为这些类型定义的显式类型转换运算符.
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.
您可以使用 AutoMapper (可从NuGet获取)在匿名类型和您的类之间动态映射
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:
这篇关于如何将匿名类型转换为已知类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!