gpt4 book ai didi

c# - 如何将匿名类型转换为已知类型

转载 作者:行者123 更新时间:2023-11-30 13:56:49 27 4
gpt4 key购买 nike

我有一个匿名类型变量。此变量是从另一个函数获取的,我们无法更改它。

// 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 有很多属性

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

最佳答案

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

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

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

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

enter image description here

关于c# - 如何将匿名类型转换为已知类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24257872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com