简体   繁体   English

C# 中的按需编译时代码生成

[英]On-demand compile-time code generation in C#

I am working in C# and I have a task I would solve in C++ using a template class.我在 C# 中工作,我有一个任务,我将使用模板类在 C++ 中解决。 However, I cannot use C# generics because the types passed in to the template don't inherit from a single base class or implement a common interface.但是,我不能使用 C# 泛型,因为传递给模板的类型不是从单个基类继承的,也不是实现公共接口的。

Right now I'm using T4 to generate separate code for every type I use, but I want this to happen automatically at compile time based on the code I've written, instead of manually maintaining a list in the text template file.现在我正在使用 T4 为我使用的每种类型生成单独的代码,但我希望这在编译时根据我编写的代码自动发生,而不是手动维护文本模板文件中的列表。

Is there syntax in the Text Template Transformation Toolkit that would, in effect, work the way templates do in C++? Text Template Transformation Toolkit 中的语法是否与 C++ 中的模板一样有效?

Edit:编辑:

Let's say I have this tt file:假设我有这个 tt 文件:

    <# string[] typeNameStrings = new string[2] {"Vector2d", "Vector3d"};
       foreach (string s in substitutions) 
       { #>
           public class SumCalculator<#= s #>
           {
               public <#= s #> sum;
               public SumCalculator<#= s #>(<#= s #> a, <#= s #> b)
               {
                   sum = a + b;
               }
           }
    <# } #>

I don't want to maintain the array typeNameStrings and then use the generated classes SumCalculatorVector2d , SumCalculatorVector3d , etc. Instead, I want to get as close to C++ template functionality as possible (ie SumCalculator<WhateverClass> ).我不想维护数组typeNameStrings然后使用生成的类SumCalculatorVector2dSumCalculatorVector3d等。相反,我想尽可能接近 C++ 模板功能(即SumCalculator<WhateverClass> )。 How do I do that?我怎么做?

If I understand you correctly, you're talking about C++'s duck typing mechanism, where it relies on the compile time expansion of templates to figure out the actual code to generate for each separate instance of the template class.如果我理解正确的话,您是在谈论 C++ 的鸭子类型机制,它依赖模板的编译时扩展来确定要为模板类的每个单独实例生成的实际代码。

C# doesn't have that, the class code is generated once in its generic form -- that's why there's a requirement that objects used in it abide by normal object rules (your common interface/class requirement). C# 没有,类代码以其通用形式生成一次——这就是为什么要求其中使用的对象遵守正常的对象规则(您的通用接口/类要求)。

However, C# does have run-time duck typing using the dynamic keyword.但是,C# 确实具有使用dynamic关键字的运行时鸭子类型。 For a (small) performance penalty, and (more importantly) loss of compile-time error checking, you can simply declare your object dynamic and call functions and access fields on it as if you were using C++ templates.对于(小的)性能损失和(更重要的)编译时错误检查的损失,您可以简单地声明您的对象dynamic并调用函数并访问其上的字段,就像您使用 C++ 模板一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM