C#Excel VSTO:get_Range()和Range()之间的区别

C# Excel VSTO: Difference between get_Range() and Range()
2020-11-21
  •  译文(汉语)
  •  原文(英语)

我试图了解Worksheet.Range()和Worksheet.get_Range()之间的区别.请看下面两行代码:

Globals.ThisWorkbook.Worksheets["Sheet1"].Range("A4").Value2 = "test";

这将在工作表上标记为"Sheet1"的单元格A4上打印"测试".同样,

Globals.ThisWorkbook.Worksheets["Sheet1"].get_Range("A4").Value2 = "test";

应该产生相同的结果,相反我得到了:

'System.__ComObject' does not contain a definition for 'get_Range

有人可以解释何时以及如何使用get_Range()吗?

有什么性能上的好处?

速聊1:
许多Office索引器返回类型为object的值,大致等于ArrayList之类的.NET 1.x集合对象.映射到__ComObject,即COM接口的RCW.它没有get_Range()方法,只有强类型接口才有.使用Range会调用后期绑定的属性getter.您必须转换为WorkSheet才能使用get_Range().这并不罕见,需要分解这么长的语句,并且许多程序员都喜欢IntelliSense提示.
解决过程1

在C#代码中,属性在内部X产生名为get_X和的方法set_X.因此,get_Range("A4")应改为Range["A4"].有关示例,请参阅此MSDN文档中第一个示例中的代码.

我怀疑您是否会看到性能差异,尽管在大多数性能问题中,答案都是"尝试并比较时间".

I am trying to understand the difference between Worksheet.Range() and Worksheet.get_Range(). Take the two lines of codes below:

Globals.ThisWorkbook.Worksheets["Sheet1"].Range("A4").Value2 = "test";

This will print "test" on cell A4 on worksheet labelled "Sheet1". Similarly,

Globals.ThisWorkbook.Worksheets["Sheet1"].get_Range("A4").Value2 = "test";

should produce the same result, instead I got:

'System.__ComObject' does not contain a definition for 'get_Range

Can someone explain when and how to use get_Range()?

Is there any performance benefit?

Talk1:
A lot of the Office indexers return a value of type object, roughly equivalent to the .NET 1.x collection objects like ArrayList. Which maps to __ComObject, the RCW for a COM interface. It has no get_Range() method, only the strongly typed interface does. Using Range invokes the late-bound property getter. You'd have to cast to WorkSheet to use get_Range(). Which is not uncommon, breaking up such a long statement is desirable and many programmers like the IntelliSense hints.
Solutions1

In C# code, a property X produces methods named get_X and set_X under the hood. Therefore, get_Range("A4") should instead be written as Range["A4"]. See the code in the first example in this MSDN document for an example.

I doubt you will see any performance difference, though as in most performance questions the answer is "try it and compare times".

转载于:https://stackoverflow.com/questions/28333313/c-sharp-excel-vsto-difference-between-get-range-and-range

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入