Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the custom generics based on. Net

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to understand the custom generics based on .NET". In the daily operation, I believe that many people have doubts about how to understand the custom generics based on .NET. The editor consulted all kinds of materials and sorted out the simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to understand the custom generics on the basis of .NET"! Next, please follow the editor to study!

The specific analysis is as follows:

Generics are frequently used in .NET, and in console applications, System.Collection.Generics namespaces are introduced by default, which provides the generics we often use: List and Dictionary, which I believe anyone who has used them knows their power. There is also a simple generic type that we often use: System.Nullable, a nullable type. We can:

System.Nullable nullableInt

Declare a nullable int type, which is simplified by the C # syntax. Usually we don't write this, but rather:

Int? NullableInt

The following focuses on how to customize generics.

Define generic classes

Creating a generic class requires angle bracket syntax in the class definition:

The copy code is as follows:

Class MyGenericClass

{

...

}

T can be any identifier, as long as you follow the naming rules.

You can use types in the return types of class members, method parameter types, and so on, for example:

The copy code is as follows:

Class MyGenericClass

{

Private T1 t1Object

Public MyGenericClass (T1 item)

{

T1Object = item

}

Public T1 T1Object

{

Get

{

Return t1Object

}

}

}

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

The copy code is as follows:

Class MyGenericClass

{

Private T1 t1Object

Public MyGenericClass ()

{

T1Object = new T1 ()

}

}

Because we don't know if 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 don't know its reference type or value type, then default comes in handy:

The copy code is as follows:

Public MyGenericClass ()

{

T1Object = default (T1)

}

If it is a value type, the value 0 is assigned, and the reference type is assigned the value null.

Constraint type

When defining generics, we can constrain the type, which is achieved by the where keyword:

The copy code is as follows:

Class MyGenericClass where T: constraint1,constraint

{

...

}

Constraint defines constraints, with multiple constraints separated by commas, if there are multiple types:

The copy code is as follows:

Class MyGenericClass where T1: constraint1 where T2: constraint

{

...

}

Here are some available constraints

Constraint description

Where T:struct uses structural constraints, and type T must be a value type

The where T:calss class constraint specifies that type T must be a reference type

Where T:interface specifies that the type T must implement either an interface or an interface

Where T:base-class specifies that the type T must be or derive from the base class.

Where T:new () specifies that type T must have a default constructor

The following combined with the above knowledge to give an example: (PS do not see how much code is actually very simple to watch patiently)

Define four classes Animal, Cow, Chicken and SuperCow first

The copy code is as follows:

# 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

/ / subclass of Cow Animal to implement virtual methods

Public class Cow:Animal

{

Public Cow (string name):

Base (name)

{

}

Public override void MakeANoise ()

{

Console.WriteLine ("{0} says' moodies'", 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)

}

}

/ / subclass of Cow, 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 supermarkets'", name)

}

}

Once the class is ready, we can begin to define our generics:

The copy code is as follows:

/ / inherits the iterator interface, so it is convenient to use Foreach to constrain its type to Animal and its subclasses

Public class Farm:IEnumerable where T: Animal

{

Private List animals = new List ()

Public List Animals

{

Get

{

Return animals

}

}

/ / iterator

Public IEnumerator GetEnumerator ()

{

Return animals.GetEnumerator ()

}

IEnumerator IEnumerable.GetEnumerator ()

{

Return animals.GetEnumerator ()

}

/ / execute MakeANoise () of all animal

Public void MakeNoises ()

{

Foreach (T animal in animals)

{

Animal.MakeANoise ()

}

}

/ / execute Feed () of all animal

Public void FeedTheAnimals ()

{

Foreach (T animal in animals)

{

Animal.Feed ()

}

}

/ / obtain the cow in animals

Public Farm GetCows ()

{

Farm cowFarm = new Farm ()

Foreach (T animal in animals)

{

If (animal is Cow)

{

CowFarm.Animals.Add (animal as Cow)

}

}

Return cowFarm

}

}

Now that the generics are defined, we call it by writing code:

The copy code is as follows:

Class Program

{

Static void Main (string [] args)

{

Farm farm = new Farm ()

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 dairyFarm = farm.GetCows ()

DairyFarm.FeedTheAnimals ()

Foreach (Cow cow in dairyFarm)

{

If (cow is SuperCow)

{

(cow as SuperCow) .Fly

}

}

Console.ReadKey ()

}

}

At this point, the study on "how to understand the basic custom generics of .NET" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report