且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

传递COM对象在C#中的参数

更新时间:2023-02-09 14:48:43

这已无关,与COM对象,它只是C#的规则。您可以将引用类型没有传递到退出 REF 参数除非引用是同一类型作为参数类型

否则,将允许不安全的场景,如以下

 公共无效掉期(Ref对象的值){
  值= typeof运算(对象);
}

字符串str =富;
掉期(出STR); //字符串现在有一个类型???
 

现在一个字符串引用所指的对象是谁的类型是键入这是错误的,非常不安全。

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;
    }
}

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.