我有 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();
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句