我一直在努力獲得一個演員工作的類具有自己的集合。在使用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