. 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;

Declare 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.

 

Define generic classes

To create a generic class, you must 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 the class member, for example:

class MyGenericClass<T1, T2, T3>{    private T1 t1Object;    public MyGenericClass(T1 item)    {        t1Object = item;    }    public T1 T1Object    {        get        {            return t1Object;        }    }}

Note that you cannot assume what type is provided. The following code cannot be executed:

class MyGenericClass<T1, T2, T3>{    private T1 t1Object;    public MyGenericClass()    {        t1Object = new T1();    }}

Because we do not know whether T1 has a public default constructor.

 

Default keyword

If we define a generic field and we want to initialize it in the constructor, but we do not know whether its reference type is a value type, then default is useful:

public MyGenericClass(){    t1Object = default(T1);}

If the value type is set to 0, the value of the reference type is null.

 

Constraint type

When defining a generic type, we can constrain the type by using the where Keyword:

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{    ...}

The following are some available constraints:

Constraints

Where T: struct uses structure constraints. The type T must be a value type.

Where T: specified by calss class constraints. The type T must be a reference type.

Where T: The specified type of interface T must be implemented as an interface or an interface

Where T: base-class the specified type T must be a base class or derived from a base class

Where T: new () the specified type T must have a default constructor.

 

The following is an example based on the above knowledge :(PS. Don't see the code too much. It's actually very easy to be patient.)

Define four classes: Animal, Cow, Chicken, and SuperCow.

# 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;} public void Feed () {Console. writeLine ("{0} has been fed. ", name);} public abstract void MakeANoise () ;}# endregion
// Cow Animal subclass, implements the virtual method public class Cow: Animal {public Cow (string name): base (name) {} public override void MakeANoise () {Console. writeLine ("{0} says 'moo! '", Name );}}
// Chicken class, Animal subclass public class Chicken: Animal {public Chicken (string name): base (name) {} public override void MakeANoise () {Console. writeLine ("{0} says 'cluck '", name );}}
// Cow subclass, which has its own method: 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 class is ready, we can start to define our generics:

// Inherits the iterator interface, so that 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 ;}}

After the generic type is defined, we use code to call it:

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();        }    }

Result:

This generic is OK.

-- Stay hungry! Stay foolish!

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.