由于我正在使用的现有框架,方法调用返回一个SortedList对象.因为我写了这个调用的另一面,我知道它实际上是一个SortedList.虽然我可以继续使用SortedList,但使用泛型可以更好地传达我的意思.那么,如何将非泛型的SortedList更改为适当类型的通用SortedList?
背景是调用是使用SoapFormatter的远程过程调用.SoapFormatter不实现泛型(谢谢你,微软).我无法更改格式化程序,因为一些非.Net程序也对服务使用其他方法调用.
我希望我的代理调用如下所示:
public SortedList<string, long> GetList(string parameter)
{
return _service.GetList(parameter);
}
Run Code Online (Sandbox Code Playgroud)
由于SoapFormatter的要求,GetList调用的接口如下所示:
public SortedList GetList(string parameter);
Run Code Online (Sandbox Code Playgroud)
您不能直接转换,因为SortedList它实际上不是SortedList<T>,即使它只包含类型的元素T.
为了将其转换为适当的类型,您需要创建一个SortedList<T>并将所有元素添加到其中.
供您使用的转换函数:
static SortedList<TKey,TValue> StronglyType<TKey,TValue>(SortedList list) {
var retval = new SortedList<TKey,TValue>(list.Count);
for(int i=0; i<list.Count; i++)
retval.Add((TKey)list.GetKey(i), (TValue)list.GetByIndex(i));
return retval;
}
Run Code Online (Sandbox Code Playgroud)
foreach(DictionaryEntry entry in list)由于隐式转换要取消装箱,等效方法稍微慢一些DictionaryEntry(您始终需要转换为 TKey/TValue)。
大概的性能开销:在我的旧机器上,这个函数需要 100 毫秒来转换 1000 个列表,每个列表有 1000 个条目。