[英]List interface: from Java to C#
I'm a Java programmer learning C# these days. 这些天我是一名学习C#的Java程序员。
Usually in Java when using lists, it should be preferrable programming against its interface in order to switch between implementations: 通常在Java中使用列表时,它应该是针对其接口的优先编程,以便在实现之间切换:
List<Object> list = new ArrayList<Object>();
//or
list = new LinkedList<Object>();
What about C# ? C#怎么样? Does exist a similar approach? 是否存在类似的方法? Can someone show me an example? 有人能告诉我一个例子吗? Since now I'm building a list this way, but I don't think List is an interface: 从现在开始我以这种方式构建一个列表,但我不认为List是一个接口:
List<int> list = new List<int>();
list.Add(2);
In .NET it is also preferable to work with the highest possible object in the hierarchy. 在.NET中,最好使用层次结构中可能性最高的对象。 You could use the IList<T>
interface: 您可以使用IList<T>
接口:
IList<int> list = new List<int>();
list.Add(2);
And if you don't need to access the list by index you could also use the ICollection<T>
interface which is even higher in the hierarchy. 如果您不需要通过索引访问列表,您还可以使用ICollection<T>
接口,该接口在层次结构中更高。
Or if you only want to enumerate through the list you could use the highest possible interface which is IEnumerable<T>
: 或者,如果您只想枚举列表,则可以使用最高可能的接口,即IEnumerable<T>
:
IEnumerable<int> list = new List<int>(new[] { 1, 2, 3 });
foreach(int item in list)
{
...
}
IList<int> = new List<int>();
在C#中它很容易 - 如果它以I
为界面开始。
List<T>
implements a number of interfaces, including IList<T>
and ICollection<T>
. List<T>
实现了许多接口,包括IList<T>
和ICollection<T>
。 You may need to examine your code to determine which interface is most appropriate. 您可能需要检查代码以确定哪个接口最合适。
In .net IList<T>
is the interface. 在.net中, IList<T>
是接口。 And you can assign it any of the interface's implementations eg, List<T>
. 您可以为其分配任何接口的实现,例如List<T>
。 See the implementations of this interface: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx#inheritanceContinued 请参阅此接口的实现: http : //msdn.microsoft.com/en-us/library/6sh2ey19.aspx#inheritanceContinued
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.