Passing COM objects as parameters in C#
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.
精彩评论