传递COM对象在C#中的参数 [英] Passing COM objects as parameters in C#

查看:126
本文介绍了传递COM对象在C#中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下code,有人可以解释为什么我可以通过一个COM对象作为参数值,而不是作为一个参考参数?

 私人无效TestRelease()
{
    Excel.Workbook工作簿= excel.ActiveWorkbook;
    ReleaseVal(练习册); // 好
    ReleaseRef(REF工作簿); // 失败
}

私人无效ReleaseVal(obj对象)
{
    如果(OBJ!= NULL)
    {
        对Marshal.ReleaseComObject(OBJ);
        OBJ = NULL;
    }
}

私人无效ReleaseRef(Ref对象OBJ)
{
    如果(OBJ!= NULL)
    {
        对Marshal.ReleaseComObject(OBJ);
        OBJ = NULL;
    }
}
 

解决方案

这已无关,与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.

这篇关于传递COM对象在C#中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆