C# 宏风格泛型

发布于 2024-11-09 06:28:42 字数 449 浏览 0 评论 0原文

我正在寻找一种方法来拥有仅在编译时存在的泛型,以实现代码重用:不必复制/粘贴类和方法。基本上只是文本替换,就像宏一样,带有一些类型检查。更像是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与酒说心事 2024-11-16 06:28:42

虽然 C# 没有 C++ 样式的模板,但您可以尝试使用 T4 (文本模板转换工具包) 来模仿它们。

您的文件将类似于:

<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#
    foreach (var T in new[]{"instantiate","for","these","types"})
    {
#>      

class FakeGeneric<#=T#>
{
    <#=T#> FakeGenericField;
}

<#  } #> 

这将生成如下类型:

class FakeGenericinstantiate
{
    instantiate FakeGenericField;
}

class FakeGenericfor
{
    for FakeGenericField;
}

// etc

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:

<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#
    foreach (var T in new[]{"instantiate","for","these","types"})
    {
#>      

class FakeGeneric<#=T#>
{
    <#=T#> FakeGenericField;
}

<#  } #> 

This would generate the types like this:

class FakeGenericinstantiate
{
    instantiate FakeGenericField;
}

class FakeGenericfor
{
    for FakeGenericField;
}

// etc

There's a page on MSDN about using T4 to generate code like this.

半步萧音过轻尘 2024-11-16 06:28:42

它们被称为模板(而不是“宏样式泛型”),并且它们在 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#.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文