Why do you need C # generic collection list ;, and general usage

Initial contact with the generic list <T> Shihai not able to understand, along with continuous learning, summed up the preliminary list <T> generic collection, we will present three issues for the generic collection, what is generic? With the hash table, two-dimensional arrays, dictionaries and other types Why do you need a generic collection? It is what a powerful programmers love?

Prior to this, we all know that both C # or C, C ++ language, they have the advantage I will not go into details, but they are nothing less than a place where people have a headache, that is, they are strongly typed language, value types, reference types, packing, unpacking, simply means that different types of values ​​can not be directly assigned, must be the same type of value assigned to each other, or you, for cattle began to think through forced conversion, you can not have a types, to avoid this situation, so, generics will naturally born.

Write generic code means writing code libraries available from a code perspective. In simple terms, it refers to the use of generics is a special syntax can be written in the widely reusable code libraries. That is the advantage that a certain block of code reuse, in general, C # class is a basic unit, when combined generic classes and how amazing effect will happen will give a simple example talk generic code reuse of this powerful application.

class NewContainer<item>

{

private  item_contained;

public  item MyProperty{

get{return _contained;}

}

set{_contained=value;}

}

Behind NewContainer identifier is enclosed in angle brackets. In angle brackets is the identifier item. Use the logo in line with angle brackets to define generic. Note that the item is not a type, but the type of placeholder you can think of it as a pit, then what kind of things (value types) specific place you can not have control of.

The following is an example of the type used type NewContainer

Newcontainer<int> container=new Newcontainer<int>();

container.MyProperty=2;

int  value=container.MyProperty;

Wherein Newcontainer an int type used in angle brackets at the point of definition. int type defined in place of the placeholder Newcontainer Item, int data type is defined as a member of the same, may be a class type double, string type, etc., may be customized, such as Newcontainer <Person> person = new Newcontainer <Person> (); which is a custom class Person

如:class Person{string name

int age;

public  string{}

}

 

Published 21 original articles · won praise 8 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_40405758/article/details/80056829