I'm a Java programmer learning C# these days.
Usually in Java when using lists, it should be preferrable programming against its interface in order to switch between implementations:
List<Object> list = new ArrayList<Object>();
//or
list = new LinkedList<Object>();
What about 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<int> list = new List<int>();
list.Add(2);
In .NET it is also preferable to work with the highest possible object in the hierarchy. You could use the IList<T>
interface:
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.
Or if you only want to enumerate through the list you could use the highest possible interface which is 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>
. You may need to examine your code to determine which interface is most appropriate.
In .net IList<T>
is the interface. And you can assign it any of the interface's implementations eg, List<T>
. See the implementations of this interface: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx#inheritanceContinued
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.