开发者

Passing COM objects as parameters in C#

开发者 https://www.devze.com 2023-01-13 19:09 出处:网络
Given the following code, can someo开发者_开发技巧ne explain why I can pass a COM object as a value parameter but not as a reference parameter?

Given the following code, can someo开发者_开发技巧ne 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;
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消