Erw*_*yer 6 c# linq immutability base-class-library
我遇到了一个似乎非常奇怪的错误ImmutableArray<>(使用BCL Immutable集合v1.0.12.0,运行时.NET 4.5):
我在同一名称空间下的同一源文件中完全具有以下两个相同的结构:
public struct WeightedComponent {
public readonly IComponent Component;
public readonly decimal Weight;
public WeightedComponent(IComponent component, decimal weight) {
this.Component = component;
this.Weight = weight;
}
}
public struct WeightedComponent2 {
public readonly IComponent Component;
public readonly decimal Weight;
public WeightedComponent2(IComponent component, decimal weight) {
this.Component = component;
this.Weight = weight;
}
}
Run Code Online (Sandbox Code Playgroud)
以下将抛出异常:
var elements1 = new[] { 1, 2, 3 }.Select(wc => new WeightedComponent(null, 0)).ToImmutableArray();
var foo = elements1.Select((e1, i1) => elements1.Select((e2, i2) => 0).ToArray()).ToArray();
if (foo.Length != 3) throw new Exception("Error: " + foo.Length); //Error: 1
var elements2 = new[] { 1, 2, 3 }.Select(wc => new WeightedComponent2(null, 0)).ToImmutableArray();
var foo2 = elements2.Select((e1, i1) => elements2.Select((e2, i2) => 0).ToArray()).ToArray();
if (foo2.Length != 3) throw new Exception("Error: " + foo.Length);
Run Code Online (Sandbox Code Playgroud)
如果我将elements1投射到ToArray()第一行而不是ToImmutableArray(),那么一切正常.
两个结构之间的唯一区别是WeightedComponent之前代码广泛使用,而WeightedComponent2以前从未使用过(这就是为什么再现错误可能并不明显).
elements1在同一个表达式中迭代两次似乎与问题有关,好像我删除它的Select工作正常,但没有这样的问题elements2.它似乎与后面的代码ImmutableArray<>考虑两种结构的方式有关(可能有一个缓存机制?)
你知道是什么原因引起的吗?
这是由于ImmutableArray<T>枚举器中的错误导致的,该错误在您第一次枚举集合的空实例时触发。NuGet软件包的未来版本将解决此问题。同时,我强烈建议您避免使用ImmutableArray<T>。