为什么从C#4.0使用COM库需要如此大量地使用动态类型? [英] Why do COM libraries used from C# 4.0 require such heavy use of dynamic types?

查看:185
本文介绍了为什么从C#4.0使用COM库需要如此大量地使用动态类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#4.0演示中,我看到许多使用动态类型的代码。例如,以下代码设置Excel单元格的值:

In the C# 4.0 demos, I'm seeing lots of code that uses the dynamic type. For example, the following code sets the value of an Excel cell:

excel.Cells [1,1] .Value = ...

excel.Cells[1, 1].Value = ...

但是,你也可以使用一个转换以早期绑定的方式访问单元格:

However, you can also access the cell in an early bound manner with a cast:

(Range)excel.Cells [ 1])。Value = ...;

((Range)excel.Cells[1, 1]).Value = ...;

为什么Excel COM库首先将Cell类型描述为Range类型?类似地,以下方法的所有参数都是动态的:

Why don't the Excel COM library just describe the Cell type as a Range type in the first place? Similarly, all the arguments to the following method are dynamic:

excel.ActiveWorkbook.Charts.Add(...)

excel.ActiveWorkbook.Charts.Add(...)

为什么参数不是静态的?看看Excel对象模型,到处都有动态类型。这是由于在COM的表现力的限制?在COM库中使用动态类型而不是静态类型时,是否有模式?

Why couldn't the arguments have been static? Looking at the Excel object model, there are dynamic types everywhere. Is this due to limitations in the expressiveness in COM? Is there a pattern to when dynamic types rather than static types are used in COM libraries?

推荐答案


在C#4.0演示中,我看到许多使用动态类型的代码。

In the C# 4.0 demos, I'm seeing lots of code that uses the dynamic type.

由于 是C#4.0中最大的变化之一,如果这不是,我会非常惊讶。 意味着您应立即开始使用动态编写所有代码 - 只是您应该可以识别可能有用。

Since dynamic is one of the biggest changes in C# 4.0, I'd be hugely surprised if this wasn't the case. That doesn't mean you should immediately start writing all your code with dynamic - simply that you should recognise when it might be useful.

当然,方差和可选/命名参数的更改也很受欢迎,但是做一个更短的演示。

The variance and optional/named argument changes are appreciated too, of course - but make a much shorter demo.

历史上,Office(特别是)一直是这样的一个猪,对于自动化Office的人来说这是一个大事。

Historically, Office (in particular) has been such a pig to program against that this is a "big thing* for people who automate Office.


  • 消费COM(特别是Office)的人

  • 消费DLR类型的人(IronPython等)

  • 到动态系统如javascript(Silverlight等)

我个人认为动态彻底改变了我在C#中编程的方式,但对某些人来说是很大的:

Personally, I don't expect dynamic to revolutionise the way I program in C#, but it is big for some people:

这篇关于为什么从C#4.0使用COM库需要如此大量地使用动态类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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