假设我已经编写了自己的方法来反转列表.
public static void MyReverse<T>(List<T> source)
{
var length = source.Count;
var hLength = length / 2;
for (var i = 0; i < hLength; i++)
{
T temp = source[i];
source[i] = source[length - 1 - i];
source[length - 1 - i] = temp;
}
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它,它的工作原理.
var fooList = new List<Foo>();
MyReverse(fooList);
Run Code Online (Sandbox Code Playgroud)
如果我想要反转多个列表,我会这样称呼它.
var fooList = new List<Foo>();
var barList = new List<Bar>();
var bazList = new List<Baz>();
MyReverse(fooList);
MyReverse(barList);
MyReverse(bazList);
Run Code Online (Sandbox Code Playgroud)
如果我想要反转任意数量的列表,我会尝试:
public static void Main(string[] args)
{
var lists = new List<object>
{
new List<Foo>(),
new List<Bar>(),
new List<Bar>()
};
ReverseLists(lists);
}
public static void ReverseLists(List<object> sourceLists)
{
foreach (var sourceList in sourceLists)
{
MyReverse(sourceList); // Error: Type arguments cannot be inferred from usage
}
}
Run Code Online (Sandbox Code Playgroud)
但这会引发编译时错误.我正在尝试做什么 - 可以ReverseLists实施该方法吗?
Sri*_*vel 10
假设你有一个像这样的静态方法
public static class ReverseHelper
{
public static void MyReverse<T>(IList<T> source)
{
var length = source.Count;
var hLength = length / 2;
for (var i = 0; i < hLength; i++)
{
T temp = source[i];
source[i] = source[length - 1 - i];
source[length - 1 - i] = temp;
}
}
}
Run Code Online (Sandbox Code Playgroud)
借助非泛型接口和泛型类,您可以执行此操作.
public interface IReverser
{
void Reverse();
}
public class ListReverser<T> : IReverser
{
private readonly IList<T> source;
public ListReverser(IList<T> source)
{
this.source = source;
}
public void Reverse()
{
ReverseHelper.MyReverse<T>(source);
}
}
static void Main(string[] args)
{
var lists = new List<IReverser>
{
new ListReverser<Foo>(new List<Foo>()),
new ListReverser<Bar>(new List<Bar>()),
new ListReverser<Bar>(new List<Bar>())
};
foreach (var reverser in lists)
{
reverser.Reverse();
}
}
Run Code Online (Sandbox Code Playgroud)
我用过IList<T>而不是List<T>支持更多类型; 如果你想要List<T>你可以把它放回去.
根据我上面的评论......
传递时,编译器无法隐藏推断T的类型object(这实际上是发生了什么)
但是有一个更简单的选择-这是刚刚放弃使用泛型,和你MyReverse方法的签名更改为public static void MyReverse(IList source)(和其他地方代替List<object>用IList)
即:
public static void Main(string args[])
{
var lists = new List<IList>
{
new List<Foo>(),
new List<Bar>(),
new List<Bar>()
};
ReverseLists(lists);
}
public static void MyReverse(IList source)
{
var length = source.Count;
var hLength = length / 2;
for (var i = 0; i < hLength; i++)
{
var temp = source[i];
source[i] = source[length - 1 - i];
source[length - 1 - i] = temp;
}
}
public static void ReverseLists(List<IList> sourceLists)
{
foreach (var sourceList in sourceLists)
{
MyReverse(sourceList); // Error: Type arguments cannot be inferred from usage
}
}
public class Foo
{
}
public class Bar
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
590 次 |
| 最近记录: |