. NET-based custom generics and. net-based custom generics

Source: Internet
Author: User

. NET-based custom generics and. net-based custom generics

In. NET is frequently used in generics. In the console application, System is introduced by default. collection. generics namespace, which provides the generic types that we often use: List <T> and Dictionary <T>. I believe all of them know their power. There is also a simple generic: System. Nullable <T>, which can be empty. We can: System. nullable <int> nullableInt; declares an empty int type. Since the C # syntax simplifies this, we usually do not write it like this, but write it like this: int? NullableInt The following describes how to customize generics. To create a generic class, you need to use the angle brackets syntax in the class definition: class MyGenericClass <T> {...} T can be any identifier, as long as it complies with the naming rules. The type can be used in the return type and method parameter type of class members, for example, copying the code class MyGenericClass <T1, T2, T3> {private T1 t1Object; public MyGenericClass (T1 item) {t1Object = item;} public T1 T1Object {get {return t1Object ;}} copy the code. Note that if you cannot assume what type is provided. The following code cannot be executed: copy the code class MyGenericClass <T1, T2, T3> {private T1 t1Object; public MyGenericClass () {t1Object = new T1 ();}} copy the code because we do not know whether T1 has a public default constructor. If we define a generic field for the default keyword, we want to initialize it in the constructor, but we do not know whether it is of reference type or value type, so default is used: public MyGenericClass () {t1Object = default (T1);} if it is a value type, it is assigned 0, and the reference type is assigned null. When defining a generic type, we can use the where keyword to implement: class MyGenericClass <T1> where T: constraint1, constraint {...} constraint defines constraints. Multiple constraints are separated by commas. If there are multiple types: class MyGenericClass <T1, T2> where T1: constraint1 where T2: constraint {...} here are some available constraints: where T: struct uses structure constraints. The type T must be a value type where T: calss class constraint, and the type T must be a reference type where T: interface specified type T must be implemented as an interface or an interface where T: base-class specified type T must be a base class or derived from the base class where T: new () the specified type T must have a default structure. Use the above knowledge in the function below to give an example: (PS should not see more code, but it is actually very easy to read) define four classes: Animal, Cow, Chicken, and SuperCow to copy the Code # The region Animal virtual base class has a name attribute Feed method and a virtual method MakeANoise // The virtual base class has a name attribute Feed. method and a virtual method MakeANoise public abstract class Animal {protected string name; public string Name {get {return name;} set {name = value;} public Animal () {name = "The animal with no name";} public Animal (string newName) {name = newName;} publi C void Feed () {Console. writeLine ("{0} has been fed. ", name) ;}public abstract void MakeANoise () ;}# copy the code to copy a subclass of the Code // Cow Animal, and implement the virtual method public class Cow: animal {public Cow (string name): base (name) {} public override void MakeANoise () {Console. writeLine ("{0} says 'moo! '", Name) ;}} copy the code to copy the code // Chicken class, Animal subclass public class Chicken: Animal {public Chicken (string name): base (name) {} public override void MakeANoise () {Console. writeLine ("{0} says 'cluck '", name) ;}copy the code to copy the code to a subclass of the Code // Cow. There is a method of its own: Fly class SuperCow: cow {public SuperCow (string name): base (name) {} public void Fly () {Console. writeLine ("{0} is flying! ", Name);} public override void MakeANoise () {Console. WriteLine (" {0} says 'I am supercow! '", Name) ;}} after the copy code class is ready, we can start to define our generic: copy the code // inherits the iterator interface, in this way, you can use Foreach to constrain its type as Animal and its subclass public class Farm <T>: IEnumerable <T> where T: animal {private List <T> animals = new List <T> (); public List <T> Animals {get {return animals ;}} // iterator public IEnumerator <T> GetEnumerator () {return animals. getEnumerator ();} IEnumerator IEnumerable. getEnumerator () {return animals. getEnumerator ();} // execute MakeANoise () public void MakeNoises () {foreach (T animal in animals) {animal. makeANoise () ;}}// run the Feed () public void FeedTheAnimals () {foreach (T animal in animals) {animal. feed () ;}// get cow public Farm <Cow> GetCows () {Farm <Cow> cowFarm = new Farm <Cow> () in animals (); foreach (T animal in animals) {if (animal is Cow) {cowFarm. animals. add (animal as Cow) ;}} return cowFarm ;}copy the generic definition of the code and we will use the code to call it: copy the code class Program {static void Main (string [] args) {Farm <Animal> farm = new Farm <Animal> (); farm. animals. add (new Cow ("Jack"); farm. animals. add (new Chicken ("Vera"); farm. animals. add (new Chicken ("Sally"); farm. animals. add (new SuperCow ("Kevin"); farm. makeNoises (); Farm <Cow> dairyFarm = farm. getCows (); dairyFarm. feedTheAnimals (); foreach (Cow cow in dairyFarm) {if (cow is SuperCow) {(cow as SuperCow ). fly () ;}} Console. readKey ();}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.