问题:编写一个可以同时接受List<int>和的方法声明int[]
我的答案涉及这样的事情:
void TestMethod(object param) // as object is the base class which can accept both int[] and List<int>
但这不是预期的答案,她这么说.
任何想法如何签署方法?
你可以使用IList<int>哪两个,int[]并List<int>实现:
void TestMethod(IList<int> ints)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您仍然可以使用索引器或Count属性(是的,Count如果将数组转换为IList<T>或者,则数组具有属性ICollection<T>).这是两种类型之间最大可能的交集,允许快速访问,使用for-loops或其他支持的方法.
请注意,即使可以调用它们,也不支持某些方法Add,如果将NotSuportedException它与数组一起使用,您将在运行时获得("Collection具有固定大小").
| 归档时间: |
|
| 查看次数: |
240 次 |
| 最近记录: |