CA2000是有关IDisposable接口(interface)的警告:
我的方法用于存储上下文的缓存,如下所示:
public class RegionContext : IDisposable { /* Implement Dispose() here */ }
private Dictionary<string, RegionContext> contextCache = new ..... ();
public RegionContext GetContext(string regionCode)
{
RegionContext rc = null;
if (!this.contextCache.TryGetValue(regionCode.ToUpper(), out rc))
{
rc = new RegionContext(regionCode);
this.contextCache.Add(regionCode.ToUpper(), rc);
}
return rc;
}
您将在哪里使用
using()
语句来修复此编译器警告?我的外部类实际上在自己的实现中迭代和处理了
contextCache
中的内容。我应该抑制它,还是有办法正确消除此警告? 最佳答案
每当您具有IDisposable的返回值并且不处理该方法引发异常的情况时,都会出现此CA2000警告。在这种情况下,调用方不会获得您对象的有效实例,因此无法对其进行处理。因此,您必须。
我假设如果成功将其从缓存中拉出,则您将不希望处置该对象。在这种情况下,您需要执行以下操作以确保在所有情况下都可以丢弃您可能在本地创建的对象:
public RegionContext GetContext(string regionCode)
{
RegionContext temp = null;
RegionContext rc = null;
try
{
if (!this.contextCache.TryGetValue(regionCode.ToUpper(), out rc))
{
temp = new RegionContext(regionCode);
this.contextCache.Add(regionCode.ToUpper(), temp);
rc = temp;
temp = null;
}
return rc;
}
finally
{
if ( temp != null )
{
temp.Dispose();
}
}
}
关于c# - 使用全局缓存时如何解决CA2000 IDisposable C#编译器警告,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6684206/