【问题标题】:how to convert anonymous type to known type如何将匿名类型转换为已知类型
【发布时间】:2014-06-17 07:19:30
【问题描述】:

我有一个匿名类型变量。这个变量是从另一个函数中得到的,我们不能改变它。

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

我有一堂课:

class Myclass{
   string property1;
   string property2;
}

如何将变量a 转换为Myclass 类型。我试过了

Myclass b = (Myclass)a; 

但它不起作用。

如果我初始化:

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

它可以工作,但它需要很多代码,因为MyClass 有很多属性

谁能帮帮我?感谢您的任何回答。

【问题讨论】:

  • 你不能转换它,因为这些类型不相关。您可以使用映射库,例如automapper,如果您真的不想编写初始化代码,可以为您工作。

标签: c# class mapping anonymous-class


【解决方案1】:

您不能在这里使用强制转换,因为您既没有继承自 MyClass 的匿名类型,也没有为这些类型定义 explicit type conversion operator

您可以使用AutoMapper(可从 NuGet 获得)在匿名类型和您的类之间动态映射

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

它将匿名对象的属性按名称映射到目标类型的属性:

【讨论】:

  • @JohnNguyen 跟随链接,或者你可以简单地在 NuGet 中找到 AutoMapper
  • 感谢您让我了解转换运算符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 2010-11-27
  • 2012-05-01
  • 2020-04-18
  • 2012-01-20
相关资源
最近更新 更多