任何人都可以向我解释为什么我想在C#中使用IList而不是List?
相关问题:为什么暴露它被认为是不好的List<T>
请参阅System.Array类的定义
public abstract class Array : IList, ...
Run Code Online (Sandbox Code Playgroud)
从理论上讲,我应该能够写下这一点,并感到高兴
int[] list = new int[] {};
IList iList = (IList)list;
Run Code Online (Sandbox Code Playgroud)
我也应该可以从iList中调用任何方法
ilist.Add(1); //exception here
Run Code Online (Sandbox Code Playgroud)
我的问题不是为什么我得到一个例外,而是为什么Array实现了IList?
返回对象时,我希望在实现层次结构中备份多远?
以Java集合接口为例,这是否合适?
Collection outerMethod() {
return innerMethod();
}
List innerMethod() {
List list = new ArrayList();
//do something with the list that requires a method in the List interface
return list;
}
Run Code Online (Sandbox Code Playgroud)
或者你想使用List作为外部方法的返回?
另一个例子,
List outerMethod() {
List list = innerMethod();
//do something with the list that requires a method in the List interface
return list;
}
Collection innerMethod() {
return new ArrayList();
}
Run Code Online (Sandbox Code Playgroud)
参数示例,
void outerMethod() {
innerMethod((List) innerMethodTwo);
}
void innerMethodOne(List list) {
//do something with the list …Run Code Online (Sandbox Code Playgroud) 在C#中
IEnumerable<MyModel> test = _blah.tolist();
Run Code Online (Sandbox Code Playgroud)
现在我可以循环测试,但如何添加项目?
请不要告诉我添加项目没有意义,我已经看过那篇文章.
我想知道的是,如果我循环浏览10个项目,我该如何再添加一个项目,以便循环浏览11个项目?
也没有.Add()方法
我看到了一个类似的功能
public FuncA(string param1, IList<SqlParameter> sqlParamsList)
Run Code Online (Sandbox Code Playgroud)
我想知道为什么作者使用IList而不是List?哪一个更好?我知道它们之间的区别是一个是界面,另一个是类.所以我最后的问题是何时使用哪个?
c# ×4
ilist ×2
list ×2
arrays ×1
collections ×1
generics ×1
ienumerable ×1
interface ×1
liskov-substitution-principle ×1
oop ×1