C# 宏风格泛型
我正在寻找一种方法来拥有仅在编译时存在的泛型,以实现代码重用:不必复制/粘贴类和方法。基本上只是文本替换,就像宏一样,带有一些类型检查。更像是 C++ 模板。
我问的原因:
普通 C# 泛型坚持始终在运行时创建泛型类型(为什么?),这
1) 不仅会产生不必要的限制(例如,不能从类型参数继承,这将非常有用),
2 )但这些运行时泛型类型现在给我带来了问题,因为 .NET 无法序列化它们,因此当我将它们插入到 RichTextBox 中时,许多操作要么失败,要么抛出“无法序列化泛型类型”异常。一切都适用于非泛型类型,但我想让代码更通用来添加东西,所以我添加了泛型( C# 通用继承解决方法),它们正在破坏一切。
谢谢。
I am looking for a way to have generics which only exist at compile time for the purpose of code reuse: not having to copy/paste classes and methods. Just text replacement basically, like macros, with some type checks. More like C++ templates.
Reason why I am asking:
Normal C# generics insist on always creating generic types at run-time (why??), which
1) not only creates unnecessary limitations (e.g. cannot inherit from a type parameter, which would be very useful),
2) but these run-time generic types are creating problems for me right now because .NET cannot serialize them, so when I insert them into a RichTextBox, many operations either fail or throw "Cannot serialize a generic type" exceptions. Everything was working with non-generic types but I wanted to make the code more general to add things so I added generics ( C# Generic Inheritance workaround), and they are breaking everything.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然 C# 没有 C++ 样式的模板,但您可以尝试使用 T4 (文本模板转换工具包) 来模仿它们。
您的文件将类似于:
这将生成如下类型:
There's 一个页面MSDN 关于使用 T4 生成这样的代码。
While C# doesn't have C++-style templates, you could try using T4 (the Text Template Transformation Toolkit) to mimic them.
Your file would look something like:
This would generate the types like this:
There's a page on MSDN about using T4 to generate code like this.
它们被称为模板(而不是“宏样式泛型”),并且它们在 C# 中不存在。
如果您有兴趣,请查看D;它有很多模板元编程功能,比 C++ 或 C# 更多(而且在我看来更好)。
They're called templates (not "macro-style generics") and they do not exist in C#.
Take a look at D if you're interested; it has a lot of template metaprogramming capabilities, more (and IMO better than) C++ or C#.