問題描述
有沒有一種自動處理數組和強類型集合之間轉換的好方法? (Is there a good way to handle conversions between arrays and strongly typed collections automatically?)
Background:
I have a big solution where hundreds of functions take strongly typed collections as inparameters and using them as return values.
The solution references a generated proxy wich converts calls to a webservice that always returns collection in the format int[] or Order[] or wathever type it is. The proxy wraps them up as IntCollection or OrderCollection.
Now I want to reference the assembly directly. When I do that I get the interface against the Arrays instead of the proxy generated strongly typed collections. This of course breaks all the code.
I am looking for a smart way to handle this and avoid rewriting thousands lines of code.
Any ideas?
‑‑‑‑‑
參考解法
方法 1:
Does IntCollection
etc belong to you? You could add an implicit conversion operator:
class IntCollection : Collection<int> {
public IntCollection() : base() { }
public IntCollection(IList<int> data) : base(data) { }
public static implicit operator int[](IntCollection items) {
return items.ToArray(); // LINQ, but can do manually
}
public static implicit operator IntCollection (int[] items){
return new IntCollection(items);
}
}
Normally, this would be one of the times that interfaces (IList<Foo>
etc) help ‑ but interfaces don't often work very well in web services. Depending on what the code currently does, you might be able to do a "replace all" fix ‑ a bit drastic, though; other than that... you're going to have to change odd bits of code.
a few thoughts:
- switching to
var
(in C# 3.0) might minimize the change ‑ i.e.var orders = svc.GetOrders()
; in most cases, the different implementations will have "similar enough" APIs- resharper might be able to help with this
- using LINQ (
.ToList()
,.ToArray()
) might serve as a shim
方法 2:
Create the strongly typed collection from the array. For example you can create a generic list from an array.
int[] oIntArray;
List<int> = new List<int>(oIntArray);
(by Jon、Marc Gravell、stevehipwell)