C# macro-style generics
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 s开发者_C百科o 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.
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#.
精彩评论