gpt4 book ai didi

c# - Excel COM 互操作 - 为什么返回类型通常是动态的?

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:28 25 4
gpt4 key购买 nike

这可能是个愚蠢的问题,但我正在使用 Microsoft 的 Office/Excel Interop 类型库。

我注意到许多返回类型都是“动态”类型;例如,

Excel.Workbook wb = ...;
var ws = wb.ActiveSheet;

ws 将是“动态的”而不是作为“Excel.Worksheet”返回 - 但这是为什么呢?

在类型库不可用的情况下,我看到了动态类型化 COM 对象的好处,但在这种情况下,它是。

那么为什么要在这里使用动态类型呢?

我现在唯一能想到的可能是嵌入互操作类型时会发生什么,然后例如.Worksheet 属性是通过反射访问的,因此它的类型不是嵌入的,但需要访问。但这是一个疯狂的猜测。必须有效地手动转换这么多类型的麻烦似乎很大,所以我认为这背后一定有一些相当重要的设计决策

最佳答案

来自 here

At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time.

.....

Conversions between dynamic objects and other types are easy. This enables the developer to switch between dynamic and non-dynamic behavior.

.....

Many COM methods allow for variation in argument types and return type by designating the types as object. This has necessitated explicit casting of the values to coordinate with strongly typed variables in C#. If you compile by using the /link (C# Compiler Options) option, the introduction of the dynamic type enables you to treat the occurrences of object in COM signatures as if they were of type dynamic, and thereby to avoid much of the casting.

关于c# - Excel COM 互操作 - 为什么返回类型通常是动态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49488517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com