【发布时间】:2017-05-31 12:35:00
【问题描述】:
我一直在努力让演员为一个拥有自己集合的班级工作。在使用 List 中具有两个 TypeA 元素的根对象进行测试时,当 List 进行隐式转换时...它输入集合的 TypeA 元素的转换代码,并且因为这是树的顶部,所以返回 TypeAIntermediate无需进入 foreach 循环(完美 - SomeAs 中什么都没有)。但是当它返回转换后的实例时,它似乎在根的转换代码的顶部重新开始,就像什么都没发生一样。
据我所知,这永远不会停止。我重写了这个遵循相同格式的简化版本......希望我没有搞砸。
//These are models used in a .Net 4.5 EF6 Library
public class TypeA
{
public string TypeAStuff;
public TypeB JustOneB;
public List<TypeA> SomeAs;
public static implicit operator TypeAIntermediate(TypeA a)
{
//New up an Intermediate A to return.
TypeAIntermediate aI = new TypeAIntermediate();
//And get ready to do handle the collection... a few ways to do this.
List<TypeAIntermediate> children = new List<TypeAIntermediate>();
//...but this appears to create an infinite loop?
foreach (TypeA item in a.SomeAs)
children.Add(item); //Cast from TypeA to to TypeAIntermediate happens here but will just keeps cycling
aI.TypeAStuff = a.TypeAStuff;
aI.JustOneB = a.JustOneB;
aI.SomeAs = children;
return aI;
}
}
public class TypeB
{
public string TypeBStuff;
public static implicit operator TypeBIntermediate(TypeB b)
{
TypeBIntermediate bI = new TypeBIntermediate();
bI.TypeBStuff = b.TypeBStuff;
return bI;
}
}
//These Intermediate Classes live in a .Net35 Library - Unity cannot use Libraries compiled for later .Net Versions.
public class TypeAIntermediate
{
public string TypeAStuff;
public TypeBIntermediate JustOneB;
public List<TypeAIntermediate> SomeAs;
}
public class TypeBIntermediate
{
public string TypeBStuff;
}
【问题讨论】:
-
我没有看到这段代码会如何创建一个无限循环。你能用简化的代码重现这个问题吗?如果是这样,您是否可以包含构建
TypeA类的代码,当您尝试转换它时会进入无限循环?此外,此代码示例中的任何地方都没有递归。 -
我认为发生在 children.Add(item) (从 TypeA 项目到 Children
)的隐式强制转换运算符再次调用自身以执行隐式转换将算作递归。但是,您如何称呼具有自身成员或自身成员集合的类(可能不是递归的 - 只是真的很好奇)? -
您没有
TypeA的集合,您有TypeB的集合。如果您确实有一个正在转换的TypeA集合,那么您将进行递归,并且如果两个对象都在集合中包含另一个对象甚至它们自己,则您可能会得到一个无限循环。 -
糟糕——我确实把事情搞砸了。它应该是 TypeA 的列表。
-
如果是
TypeA的集合,您需要通过创建从TypeA到TypeAIntermediate的映射来跟踪哪些对象已被转换,然后您可以填充集合通过在地图中查找转换创建的每个TypeAIntermediate。假设你想在你的层次结构中保持循环。
标签: c# recursion casting implicit