我一直在努力获得一个演员工作的类具有自己的集合。在使用List中具有两个TypeA元素的根对象进行测试时,当List执行隐式转换时...它将输入集合的TypeA元素的转换代码,并且因为这是树的顶部,所以返回TypeAIntermediate无需进入foreach循环(即完美 - SomeAs中没有任何内容)。但是当它返回转换的实例时,它似乎重新开始在根的转换代码的顶部,就像什么都没有发生。c#转换运算符为递归集合类
据我所知,这永远不会停止。我重写了这个遵循相同格式的简化版本......希望我没有搞砸。
//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'类的代码,当你尝试转换它时会进入无限循环?此代码示例中也没有任何地方递归。 – juharr
我认为隐式强制转换发生在children.Add(item)(从TypeA项到Children)强制转换运算符再次调用自己以执行隐式强制转换将计为递归。而且,你怎么称呼一个拥有自身成员的类,或者自己的成员集合(可能不是递归的 - 实际上好奇)? –
您没有'TypeA'集合,您有'TypeB'集合。如果你确实有一个正在被转换的'TypeA'的集合,那么你将会有递归,如果两个对象都拥有另一个或者它们本身在集合中,你可以得到一个无限循环。 – juharr