gpt4 book ai didi

c# - 异常过滤器触发 CA2202?

转载 作者:行者123 更新时间:2023-11-30 17:39:42 24 4
gpt4 key购买 nike

我有一个函数,归结起来,看起来像这样:

public static string Merge(string xml1, string xml2)
{
try
{
var doc1 = XDocument.Load(new StringReader(xml1));
var doc2 = XDocument.Load(new StringReader(xml2));

// these "die" by throwing InvalidOperationException
var root1 = GetElementOrDie(doc1, Names.RootElementName);
var root2 = GetElementOrDie(doc2, Names.RootElementName);

foreach (var element in root2.Elements())
root1.Add(element);

return doc1.ToString();
}
catch (Exception e) when (!(e is InvalidOperationException))
{
throw new InvalidOperationException(e.Message, e);
}
}

在 Visual Studio 2015 下,这会生成代码分析警告 CA2202:

Object 'root2.Elements().GetEnumerator()' can be disposed more than once in method 'XmlProcessor.Merge(string, string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

如果我删除 when 子句,警告就会消失。

这是怎么回事?警告我是对的吗?

供引用:

private static XElement GetElementOrDie(XContainer container, XName elementName)
{
var element = container.Element(elementName);
if (element == null)
throw new InvalidOperationException();
return element;
}

最佳答案

我认为这是代码分析的一个问题,我会压制它。如果我将循环从:

foreach (var element in root2.Elements())
root1.Add(element);

为此公开它明确提示的枚举器:

var enumerator = root2.Elements().GetEnumerator();
while (enumerator.MoveNext())
{
XElement item = enumerator.Current;
root1.Add(item);
}

然后 CA2202 不再抛出,即使在异常上有 when 文件管理器也是如此。

关于c# - 异常过滤器触发 CA2202?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35203767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com