C# 如何传递多个泛型参数

C# 如何传递多个泛型参数,c#,.net,generics,reflection,C#,.net,Generics,Reflection,我想知道是否有一种方法可以构建一个可以接受多个泛型参数的类 这在编译时是未知的 class Something<T,V,U> 不能指定未知数量的泛型。你能得到的最接近的方法是定义所有可能的变化,或者至少定义你愿意处理的变化。例如: public abstract class Something { } public class Something<T1> : Something { } public class Something<T1, T2> :

我想知道是否有一种方法可以构建一个可以接受多个泛型参数的类 这在编译时是未知的

   class Something<T,V,U> 
不能指定未知数量的泛型。你能得到的最接近的方法是定义所有可能的变化,或者至少定义你愿意处理的变化。例如:

public abstract class Something { }
public class Something<T1> : Something { }
public class Something<T1, T2> : Something { }
public class Something<T1, T2, T3> : Something { }
public class Something<T1, T2, T3, T4> : Something { }
public class Something<T1, T2, T3, T4, T5> : Something { }
...
public抽象类Something{}
公共类某物:某物{}
公共类某物:某物{}
公共类某物:某物{}
公共类某物:某物{}
公共类某物:某物{}
...
当您不知道对象类型的泛型参数数量时,抽象类是一种有用的类型


根据您的恶意,您可能最终使用此解决方案编写了大量冗余代码,在这种情况下,您应该重新考虑泛型的使用。

您可以创建一些类,一种

public static class TypeHelper
{
    public static IEnumerable<Type> GetTypeCombination(this Type type)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(T<,>))
            return type.GetGenericArguments().SelectMany(GetTypeCombination);

        return new Type[] { type };
    }
}

public class T<T1, T2>
{
    public static IEnumerable<Type> GetTypeCombination()
    {
        return typeof(T1).GetTypeCombination()
            .Concat(typeof(T2).GetTypeCombination());
    }
}
公共静态类TypeHelper
{
公共静态IEnumerable GetTypeCombination(此类型)
{
if(type.IsGenericType&&type.GetGenericTypeDefinition()==typeof(T))
返回类型.GetGenericArguments().SelectMany(GetTypeCombination);
返回新类型[]{Type};
}
}
公共T类
{
公共静态IEnumerable GetTypeCombination()
{
返回typeof(T1).GetTypeCombination()
.Concat(typeof(T2).GetTypeCombination());
}
}
并以此作为

var list = T<int, T<string, int[]>>.GetTypeCombination().ToList();
var list=T.gettypecomposition().ToList();

要获取(传递)类型的动态列表-不确定这是最佳方法

可变通用参数?我不这么认为。使用泛型的主要目的是确保编译时的类型安全。如果您在运行时之前不知道涉及的泛型参数,那么您就无法正确使用泛型。我从来没有像我建议的那样使用它们我只是在构建某种类型的分层索引组件,其层包含一个带有不同泛型类型键的已排序字典,我想,如果存在不同数量的争论,这将使我免于陷入混乱的工作环境。谢谢你忽略了这个概念。你是想创建一个包含所有层的类吗,或者你想要更像复合模式的东西吗?对不起,伙计,我不知道复合模式是什么。我在做汉克我想了一个解决办法,我用反射得到我的t,然后在某个东西里面,我用反射在某个东西里面创建另一个东西,这可以做很多次。我会把我的答案贴出来稍后,如果我完成了一些工作。您不能传递泛型参数的可变计数,但您可以传递一个组合了多个(一对)泛型参数的类型(这对中的每个元素也可以是2的组合符),谢谢,我需要尝试一下。。现在看来这是我力所不及的。
public static class TypeHelper
{
    public static IEnumerable<Type> GetTypeCombination(this Type type)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(T<,>))
            return type.GetGenericArguments().SelectMany(GetTypeCombination);

        return new Type[] { type };
    }
}

public class T<T1, T2>
{
    public static IEnumerable<Type> GetTypeCombination()
    {
        return typeof(T1).GetTypeCombination()
            .Concat(typeof(T2).GetTypeCombination());
    }
}
var list = T<int, T<string, int[]>>.GetTypeCombination().ToList();