c# - 将嵌套数组类转换为另一个嵌套数组类c#
问题描述
我有 2 个看起来完全相同但位于不同名称空间中的类。嵌套类的一个属性是其自身的数组,它允许属性嵌套/递归(有点像命令模式)
我正在尝试将类从一个命名空间转换/转换为另一个命名空间中的类。我有以下代码:
namespace Common.Class
{
public class Root
{
public string Key { get; set; }
public Child[] Children { get; set; }
public class Child
{
public string Content { get; set; }
public Child[] RecursionChild { get; set; }
}
}
}
namespace Uncommon.Class
{
class Root
{
public string Key { get; set; }
public Child[] Children { get; set; }
public class Child
{
public string Content { get; set; }
public Child RecursionChild { get; set; }
}
}
}
主程序
static void Main(string[] args)
{
var commonRoot = new Common.Class.Root
{
Key = "1234-lkij-125l-123o-123s",
Children = new Common.Class.Root.Child[]
{
new Common.Class.Root.Child
{
Content = "Level 1 content",
RecursionChild = new Common.Class.Root.Child[] { }
}
}
};
var uncommonRoot = new Uncommon.Class.Root
{
Key = commonRoot.Key,
Children = commonRoot.Children // here I get error: Cannot implicitly convert type 'Common.Class.Root.Child[]' to 'Uncommon.Class.Root.Child[]'
};
}
解决方案
你也需要改变孩子。
因为你有那个递归的孩子,你不能只用匿名函数来完成它,因为函数必须能够调用自己,你需要一个名字。所以我们需要引入一个实名的局部函数,例如Converter
。
Uncommon.Root.Child Converter(Common.Root.Child source) => new Uncommon.Root.Child
{
Content = source.Content,
RecursiveChild = Converter(source.ResursiveChild)
};
var uncommonRoot = new Uncommon.Class.Root
{
Key = commonRoot.Key,
Children = commonRoot.Children.Select(Converter).ToArray();
};
推荐阅读
- java - 无法使用实用程序方法检查多个edittext是否为空,并且在输出toast中自定义正确的edittext id
- python - 了解 PyTorch 中 index_put 的行为
- mysql - mySql 查询——网络文件共享程序
- ruby - 无法将实例变量的值从同一类中传递给另一个(Ruby)
- api - 如何使用监视列表 ID 通过 Stocktwits API 访问消息?
- c++ - 如何在 Xcode 中获得 std::optional 支持?
- r - 将数据从excel导入R?
- sql-server - 使用 MERGE 语句更新 SCD2
- c# - DotNetZip 创建包含文件路径的子文件夹
- php - 开始日期和结束日期php之间的财政年度数组