C#宏式泛型 [英] C# macro-style generics

查看:166
本文介绍了C#宏式泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来让泛型只在编译时存在,以便重用代码:不必复制/粘贴类和方法。基本上像文本替换,就像宏一样,进行一些类型检查。更像是C ++模板。



为什么我要问:



正常的C#泛型一直坚持总是创建泛型类型在运行时(为什么??),它不仅产生不必要的限制(例如不能从类型参数继承,这将是非常有用的),

<1> / p>

2)但这些运行时泛型类型现在为我创建了问题,因为.NET无法序列化它们,所以当我将它们插入到RichTextBox中时,许多操作要么失败或抛出无法序列化泛型异常。一切都与非泛型类型工作,但我想使代码更通用的添加东西,所以我添加了泛型( C#泛型继承解决方法),并且它们正在打破一切。



谢谢。

解决方案

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



您的文件看起来像这样:

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

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

<#}#>

这会产生如下的类型:

  class FakeGenericinstantiate 
{
实例化FakeGenericField;
}

类FakeGenericfor
{
为FakeGenericField;
}

// etc

MSDN上关于使用T4生成代码的页面


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.

解决方案

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.

这篇关于C#宏式泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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