首页 > 解决方案 > 将嵌套数组类转换为另一个嵌套数组类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[]'
            };
        }

标签: c#linqrecursiondeep-copy

解决方案


你也需要改变孩子。

因为你有那个递归的孩子,你不能只用匿名函数来完成它,因为函数必须能够调用自己,你需要一个名字。所以我们需要引入一个实名的局部函数,例如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();
};

推荐阅读