我想写下面的方法
private void Foo<T, TItem>(T<TItem> param1)
Run Code Online (Sandbox Code Playgroud)
其中T必须是以TItem作为其通用信息的泛型类型.
调用示例如下:
private void Main()
{
List<int> ints = new List<int>();
Foo<List, int>(ints);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
在我的情况下,我只需要收集.实际的用例是我想编写一个方法,向ICollection添加一些东西,遗憾的ICollection是没有.Add方法只有它ICollection<T>有它.
我无法将方法更改为:
private Foo<T>(ICollection<T>)
Run Code Online (Sandbox Code Playgroud)
因为我失去了信息实际列表的类型,这对我来说比列表中的项目类型更重要.
所以上述想法诞生了,但没有奏效.
由于您只需要集合,您可以描述这样的方法:
private void Foo<T, TItem>(T param1)
where T: ICollection<TItem>
{
}
Run Code Online (Sandbox Code Playgroud)
但是在这种情况下,您需要提供特定的泛型类型(List<int>)作为第一个通用参数,您不能只使用List:
List<int> ints = new List<int>();
Foo<List<int>, int>(ints);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |