VSTO:操作 COM 对象(“一个点好,两个点坏")

VSTO: manipulating COM objects (quot;one dot good, two dots badquot;)(VSTO:操作 COM 对象(“一个点好,两个点坏))
本文介绍了VSTO:操作 COM 对象(“一个点好,两个点坏")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Excel VBA 背景,我经常会编写如下代码:

Coming from an Excel VBA background I would frequently write code such as:

Range("myRange").Offset(0, 1).Resize(1, ccData).EntireColumn.Delete

我现在正在转向 VSTO,并且一直在阅读有关 RCW 计数器等以及显式释放 COM 对象的需要.基本建议似乎是:不要将 Excel 对象的引用链接在一起(就像我上面所说的那样) - 因此一个点好,两个点坏".我的问题是,我是否正确,上面的代码不是 VSTO 的方式?如果是这样,这是否意味着我需要明确声明上述链中隐含的 3 个范围(Offset、Resize 和 EntireColumn)?

I'm now moving to VSTO, and have been reading about RCW counters, etc., and the need to explicitly release COM objects. The basic advice seems to be: don't chain together references to Excel objects (as I have above) - hence "one dot good, two dots bad". My question is, am I correct that the above code is not the way to go in VSTO? If so, does that mean that I would need to explicitly declare the 3 ranges implied in the above chain (Offset, Resize & EntireColumn)?

或者甚至是这样的:

rng.Columns.Count

哪里 rng 是一个声明的范围?我是否应该为 rng.Columns 分配一个名称以获取该范围内的列数??

where rng is a declared Range? Should I be assigning a name to rng.Columns in order to obtain the number of columns in the range??

推荐答案

两点规则"的愚蠢背后有非常有害的货物崇拜,它从版本 4 开始完全无法让 C# 程序员免于麻烦.而且它层出不穷比让 Office 程序按需退出的简单方法更痛苦.

There is very detrimental cargo cult behind that "two dot rule" silliness, it completely fails to keep C# programmers out of trouble since version 4. And it endlessly more painful than the simple way to make Office programs quit on demand.

但这不是你遇到的问题根本,货物崇拜只适用于使用自动化激活 Office 程序的进程外程序.您的代码实际上在内部 Office 程序中运行,您当然不在乎程序何时终止.因为这也会终止您的代码.

But this is not a problem you have at all, the cargo cult only applies to an out-of-process program that use Automation to activate an Office program. Your code in fact runs inside the Office program, you of course don't care when the program terminates. Because that terminates your code as well.

只需像编写常规 C# 代码一样编写代码,GC 不需要任何帮助.

Just write your code the way you'd write regular C# code, the GC does not need any help.

这篇关于VSTO:操作 COM 对象(“一个点好,两个点坏")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)