了解COM C#接口 [英] Understand COM c# interfaces

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

问题描述

该Microsoft.Office.Interop.Word._Document接口具有以下签名的方法:

The Microsoft.Office.Interop.Word._Document interface has a method with the following signature:

void Close(ref object SaveChanges = Type.Missing, ref object OriginalFormat = Type.Missing, ref object RouteDocument = Type.Missing);



我无法理解的几点:

A few points I am having trouble understanding:


  1. REF参数不能有默认值。

  2. 的默认值必须是一个常数, Type.Missing 不是

  3. 调用此方法时,我可以使用关闭(假) - 通常是ref参数需要分配的变量?

  4. 当导航到的定义在Visual Studio中键入,它带我到_Document.Type财产,但这并不具有缺少命名的属性。这是VS的错误吗?

  1. A ref parameter cannot have a default value.
  2. A default value has to be a constant, and Type.Missing is not.
  3. When calling this method, I can use Close(false) - normally a ref parameter requires an assignable variable?
  4. When navigating to the definition of Type in Visual Studio, it takes me to the _Document.Type property, but this does not have a property named Missing. Is this a bug in VS?

感谢您的任何解释。

推荐答案

有一个怪癖,在C#4版推出它不是专用于COM互操作代码,你也可以在你自己的代码。试试这个:

It is a quirk, introduced in C# version 4. It is not exclusive to COM interop code, you can also get it in your own code. Try this:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Example([Optional] object arg) { }
    static void Main(string[] args) {
        Example(   // <== Look at the IntelliSense popup here
    }
}

有在[可选]属性触发这种行为。去过撒手人寰,但从来没有在C#之前特别有用。不像在VB.NET和C ++ / CLI等语言。用C#V4出发,不同的方式解释属性和编译器将硬代码Type.Missing作为一个参数类型的可选值的对象的,尝试改变参数类型,比方说,字符串的,请注意,默认变得不同。null,如你所期望的。

It is the [Optional] attribute that triggers this behavior. Been around forever but was never particularly useful in C# before. Unlike other languages like VB.NET and C++/CLI. Starting with C# v4, it interprets the attribute differently and the compiler will hard-code Type.Missing as the optional value for an argument type of object. Try changing the argument type to, say, string and note that the default becomes different. Null, as you'd expect.

这是不是很漂亮,当然,Type.Missing是正常的C#中的对象的一个相当奇怪的默认值代码。每个人都期望的的替代。然而,它是非常实用的,在以前的4个版本的Office编写代码的互操作在C#中是一个相当可怕的锻炼。公司可以遇到麻烦时,他们做这样的东西顺便说一句,如果委员Neelie Kroes的得到风声,她会得到微软支付一个十亿欧元的罚款:)

This isn't very pretty of course, Type.Missing is a rather odd default value for object in normal C# code. Everybody would expect null instead. It is however very practical, writing Office interop code in C# in versions previous to 4 was a rather dreadful exercise. Companies can get into trouble when they do stuff like this btw, if Neelie Kroes gets wind of it she'd get Microsoft to pay a billion Euro fine for that :)

这篇关于了解COM C#接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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