gpt4 book ai didi

c# - ComWrapper 类是否明智地包装了 Interop Com 对象

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:48 24 4
gpt4 key购买 nike

我的应用程序使用了 Interop Com 对象。因此,我编写了一个包装类,以在处置中进行释放,或者如果这没有在终结器中完成的话。所以我可以使用 using 关键字来确保完成释放。

使用这种模式是一种好方法吗?还是框架中甚至有一个类正在为我做这件事?

    class ComWrapper<T> : IDisposable
{
private readonly T comObject;

private bool disposed = false;

public ComWrapper(T comObject)
{
this.comObject = comObject;
}

~ComWrapper()
{
this.Dispose(false);
}

public T ComObject
{
get
{
return this.comObject;
}
}

public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}

public void Dispose(bool disposing)
{
if (this.disposed)
{
return;
}

Marshal.FinalReleaseComObject(this.comObject);
}
}

最佳答案

我个人不会推荐这个,因为它看起来有点毫无意义。但是,我建议使用以下方法使用一个名为 Utility 的静态类:

    public static void disposeComObject<T>(ref T comObject)
{
if(Marshal.IsComObject(comObject) && comObject != null)
{
//You need to save the object
if(typeof(T) == typeof(Microsoft.Office.Interop.Excel.Workbook))
{
((Microsoft.Office.Interop.Excel.Workbook))comObject.Save();
((Microsoft.Office.Interop.Excel.Workbook))comObject.Close();
}

//You need to save the object
if(typeof(T) == typeof(Microsoft.Office.Interop.Excel.Application))
{
((Microsoft.Office.Interop.Excel.Application))comObject.Quit();
}

Marshal.ReleaseComObject(comObject);
comObject = null;
}
}

现在从代码中,你可以这样调用它

     ...
Microsoft.Office.Interop.Excel comObject = null;
try{
//Open comObject
//Here I would call some functions, and have nested exceptions
}
catch(nestedException err)
{
//Handle at your discretion
}
finally{
Utility.disposeComObject(ref comObject);
}

这是特定于 Excel 命名空间的,但调整它应该很容易。

关于c# - ComWrapper 类是否明智地包装了 Interop Com 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30013615/

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