我尝试在完成后处理对象并且我收到跟踪错误
Unable to cast object of type 'App.Entities.Security.EBSCredentialEntity' to type 'System.IDisposable
private EBSCredentialEntity _ServiceCredentialObject;
private void InitializeEBSCredentials()
{
_ServiceCredentialObject = new EBSCredentialEntity() {
UserName = System.Configuration.ConfigurationManager.AppSettings["EBS_UserName"],
//remaining code
};
}
private void DisposeEBSCredentialObject()
{
if (_ServiceCredentialObject != null)
{
((IDisposable)_ServiceCredentialObject).Dispose();
}
}
我从另一个方法调用DisposeEBSCredentialObject()
答案 0 :(得分:2)
要处置对象,其类型必须为Disposable。那么你的EBSCredentialEntity类是否是一次性的,即它是否实现了IDisposable?
如果确实如此,那么您不需要像在发布的代码中显示的那样进行投射。
答案 1 :(得分:1)
您需要实现接口IDisposable
:
public EBSCredentialEntity : IDisposable
另外,如果您使用C#6,您可以这样写:
private void DisposeEBSCredentialObject()
{
(_ServiceCredentialObject as IDisposable)?.Dispose();
}
但我们知道,_ServiceCredentialObject在设计上是IDisposable,因此,我们可以跳过转换:
private void DisposeEBSCredentialObject()
{
_ServiceCredentialObject?.Dispose();
}
答案 2 :(得分:1)
您的班级应该实施IDisposable
界面:
public class EBSCredentialEntity : IDisposable
{
public void Dispose()
{
// cleanup code here
}
}
然后你也可以使用方便的using
语句来避免直接调用Dispose
方法:
using (EBSCredentialEntity entity = new EBSCredentialEntity())
{
// ...
}