COM Interop
1. null 参数的传入
COM components don’t support parameter overloading, so for each value in a parameter list, you’ve got to pass in something, even if it does nothing.
Moreover, COM parameters are always passed by reference, which means that you can’t pass in a null value.
Instead of creating “dummy” object variables, the Type.Missing field can be used.
class Program
{
private static Object OptionalParamHandler = Type.Missing;
static void Main(string[] args)
{
Application NewExcelApp = new Application();
NewExcelApp.Worksheets.Add(ref OptionalParamHandler,
ref OptionalParamHandler, ref OptionalParamHandler,
ref OptionalParamHandler);
}
}
2. RuntimeWrappedException(new in .net 2.0)
COM errors won’t be CLS compliant, they won’t be caught with Exception, .net 2.0提供
RuntimeWrappedException封装了Non CLS-Compliant的异常.
代码一般写成:
private static void IllustrateExceptions()
{
try
{
// Something that throws an exception
}
catch (Exception ex)
{
// In 1.x this will catch only CLS-Compliant
// In 2.0 both CLS and Non CLS-Compliant will
// be caught by this block.
}
catch
{
// All exceptions, CLS-Compliant and Non CLS-Compliant are caught
}
}
3. COM interop的缺点:
-
Static members COM objects are fundamentally different from .NET types. One of the differences is lack of support for static members.
-
Parameterized constructors COM types don’t allow parameters to be passed into a constructor. This limits the control you have over initialization and the use of overloaded constructors.
-
Inheritance One of the biggest issues is the limitations COM objects place on the inheritance chain. Members that shadow members in a base class aren’t recognizable, and therefore, aren’t callable or usable in any real sense.
-
Portability Operating systems other than Windows don’t have a registry. Reliance on the Windows registry limits the number of environments a .NET application can be ported to.
如果一个.NET Class要被COM使用,就必须:
提供无参数的构造函数,暴露给COM的type和type member必须为public.
Abstract clsss 不能被COM使用.
