如何将未定义数量的类型参数传递给泛型方法?

如何将未定义数量的类型参数传递给泛型方法?

问题描述:

我有带两个类型参数中的第一个是具有我通过其类型作为第二个参数的项目的列表的类的通用方法:如何将未定义数量的类型参数传递给泛型方法?

public static TJCls GetComplexLog<TJCls, TListObj>(int logIds) where TJCls : ISplitList<TListObj> 
{ 
    //here I deserialize the string from DB to TJCls, and deserialize List<string> 
    //from DB to List<TListObj> and set the TJCls's list via the ISplitList's SetList method: 
    log.SetList(lst); 
} 

但现在的对象可以具有多于一个的列表(未知号码),所以有没有办法我可以通过任何数量的类型参数,如params

您在C#中建议的语法中的可变数量的类型参数是不可能的。也就是说,可以使用如下类型描述符的序列。

public static GetComplexLog(int logIds, IEnumerable<Type> TypeSeq) 
{ 
    // todo 
} 

使用此签名可以使用反射对类型信息做一些有用的事情,甚至可以创建实例。然而,静态类型检查约束类型,如

where TJCls : ISplitList<TListObj> 

也将是不可能的,因为在运行时反射式安全将不得不使用,可以做的是扔在违反异常最好的。

不,你不能像泛型类型参数那样传递params参数。在你的场景中,你可以传递TListObj作为方法参数,对吧?