我正在对项目进行一些代码分析并实现有意义的建议。一个建议是执行以下操作:
CA2000 : Microsoft.Reliability : In method 'Service.ParseConfigurationFile()', call System.IDisposable.Dispose on object 'new SecureString()' before all references to it are out of scope
违规行如下:
Password = me.Password.Aggregate(new SecureString(), (secureString, c) => { secureString.AppendChar(c); return secureString; })
关于如何正确执行此操作的任何想法?我已将上面的内容替换为下面的行,但我认为它不正确,因为它仍然会导致出现代码分析消息:
Password = me.Password.Aggregate(new SecureString(), (secureString, c) => { using (secureString) {secureString.AppendChar(c); return secureString;} })
编辑:根据下面@Jon 的评论,objectInstance 是一个名为 MailboxElement (me) 的自定义类的实例。它通过一个配置文件中的多个自定义部分,如下所示:
foreach (MailboxElement me in mailboxesSection.Mailboxes)
{
MailboxInformation mailboxInformation = new MailboxInformation
{
ExchangeServerWebServiceUrl = me.ExchangeServerWebServiceUrl,
MailboxFriendlyName = me.FriendlyName,
UserName = me.UserName,
Password = me.Password.Aggregate(new SecureString(), (secureString, c) => { secureString.AppendChar(c); return secureString; }),
MailboxToAccess = me.MailboxToAccess
};
// Do stuff with mailboxInformation here
}
MailboxElement
是一个实现了 ConfigurationElement 的密封类具有上述所有属性。
MailboxInformation
定义如下:
public class MailboxInformation
{
public string MailboxFriendlyName { get; set; }
public string UserName { get; set; }
public SecureString Password { get; set; }
public string ExchangeServerWebServiceUrl { get; set; }
public string MailboxToAccess { get; set; }
public string InboxFolderId { get; set; }
public string SentItemsFolderId { get; set; }
public bool MailboxSettingsDiscovered { get; set; }
}
我希望这能让事情变得更清楚......
最佳答案
您正在从聚合中返回一个 IDispoable,因此您需要处理它或简单地重新分配给 secureString
using (var secureString = new SecureString()) {
secureString = objectInstance.Password.Aggregate((secureString, c) => { secureString.AppendChar(c); return secureString; }){
}
问题更新后编辑
由于您的 MailboxInformation
对象现在获得了 IDisposable 的所有权,因此 MailboxInformation
它本身应该是 IDisposable 并处理它拥有的一次性元素
所以实现将是(类似于您的评论)
public class MailboxInformation : IDisposeable
{
//...
public SecureString Password { get; set; }
//...
void IDisposable.Dispose() {
this.Password.Dispose();
}
}
关于c# - 如何在 lambda 表达式中使用 IDisposable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11308640/