如何生成可变参数类泛型类?

问题描述 投票:0回答:1

我想要的很简单:

public class Collection<T1,...TN> where T1...TN : SomeClass {
    public static Type[] types = {typeof(T1)...typeof(TN)}
}

如何为Ns从1到N生成这样的基类(例如默认值为40)?

我最终得到了这样的.tt模板:

<#@ template hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>

using System;
using System.Collections.Generic;
using System.Text;

namespace Services
{

    public interface ICollections {
        public Type[] Types {get;}
    }

<#
int top = 10;
for (int i = 0; i<=top; i++)

{ #>
    public class Collections< <# for (int j = 0; j<=i; j++) {#> T<#=j#> <#= (j<i  )?(","):(" ") #> <# }#> > : ICollections <# for (int j = 0; j<=i; j++) {#> 
    where T<#=j#> : SomeClass <# }#>
    {
        public Type[] Types => new[] { <# for (int j = 0; j<=i; j++) {#> typeof(T<#=j#>) <#= (j<i  )?(","):(" ") #> <# }#>};
    }
<# } #>
}
c# .net .net-4.5 t4
1个回答
0
投票

您似乎已经确定了编译时间。

您是否对创建类运行时有疑问?如果是这样-我敢说这是不可能的。如果我错了,请纠正我。

© www.soinside.com 2019 - 2024. All rights reserved.