Passing COM objects as parameters in C#

2019-07-14 14:34发布

问题:

Given the following code, can someone explain why I can pass a COM object as a value parameter but not as a reference parameter?

private void TestRelease()
{
    Excel.Workbook workbook = excel.ActiveWorkbook;
    ReleaseVal(workbook);       // OK
    ReleaseRef(ref workbook);   // Fail
}

private void ReleaseVal(Object obj)
{
    if (obj != null)
    {
        Marshal.ReleaseComObject(obj);
        obj = null;
    }
}

private void ReleaseRef(ref Object obj)
{
    if (obj != null)
    {
        Marshal.ReleaseComObject(obj);
        obj = null;
    }
}

回答1:

This has nothing to do with COM objects, it's simply a rule of C#. You cannot pass a reference type to an out or ref param unless the reference is of the same type as the parameter type.

Otherwise it would allow for unsafe scenarios like the following

public void Swap(ref Object value) {
  value = typeof(Object);
}

string str = "foo";
Swap(out str); // String now has an Type???

Now a string reference refers to an object who's type is Type which is wrong and very unsafe.



标签: c# .net com