【发布时间】:2012-07-02 15:09:49
【问题描述】:
我的 T4 模板实例化了一个 Excel COM 对象以读取一些单元格值并从中创建 C# 类。我首先用常规 C# 编写了 Excel 读取逻辑,效果很好。我在这个测试中使用的代码 sn-p 是:
Worksheet xlWorkSheet;
string cellContents = xlWorkSheet.Cells.Item[1, 1].Value;
不过,将测试代码移植到 T4 模板中是行不通的。显示如下错误:
Error 1: Compiling transformation: 'object' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
我解决这个问题的唯一方法是添加一些手动转换:
string cellContents = (xlWorkSheet.Cells.Item[1, 1] as Range).Value as string;
我的印象是 T4 使用“常规”C# 编译器,因此能够像常规代码一样处理动态绑定。但显然,存在差异。在这种情况下,我可以解决我的问题,因为我能够猜测要转换为哪种类型。但总的来说,情况并非如此。有没有办法让这种后期绑定在 T4 模板中工作?
【问题讨论】:
-
你用的是什么版本的t4?
-
不确定如何检查 T4 的版本,但我在带有 .NET 4.0 的 Visual C# 2010 Express 中使用它
-
常规 C# 可以使用 'dynamic' 关键字处理动态绑定,T4 也可以。没有也无法推断。如果您将工作表定义为动态的,那么您应该很好。
-
我确实在常规 C# 和 T4 之间看到了不同的结果——无需在 C# 中将任何内容定义为
dynamic,我引用的行可以正常工作。我尝试在 T4 中将xlWorkSheet更改为dynamic,但这也导致了错误:Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported和Compiling transformation: One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?。我没有错过这些引用,并且导入建议的类型也不起作用。 -
@GarethJ 你是对的,我还必须添加一些程序集引用才能使其正常工作(所以我缺少对
Microsoft.CSharp和System.Core的引用) .谢谢!