当前位置:网站首页>C simple understanding - generics
C simple understanding - generics
2022-06-13 03:06:00 【cathy18c】
What is generics : Generics are equivalent to a module , Loading type of material , It can be shaped into the product we want . For example, a model of a doll , There is a hole in it , Inject golden water , It's the Golden Doll , Inject mud , It's a clay doll .

T It's the type , It plays a role in the definition of the whole class Place holder The role of
How do you use it? :
class Cage<T>{……} Declaration of generic class
Cage<Dog> dogCage; Cage<Dog> Type references
dogCage=new Cage<Dog>(); Construction example
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var dogCage = new Cage<Dog>(1);
dogCage.PutIn(new Dog("Jack"));
dogCage.PutIn(new Dog("Herry"));
}
}
class Pet
{
private string name;
private int age;
public string Name { get => name; set => name = value; }
public int Age { get => age; set => age = value; }
public Pet(string name)
{
this.Name = name;
}
}
class Dog : Pet
{
public Dog(string name) : base(name) { }
}
class Cat : Pet
{
public Cat(string name) : base(name) { }
}
class Cage<T>
{
T[] array; // Define a T An array of types , For pets
private readonly int size; // The total number of pets that can be put in the cage
private int num; // The number of caged pets
public Cage(int n) // Constructor initializes
{
size = n;
num = 0;
array = new T[size];
}
public void PutIn(T p)
{
if (num < size)
{
array[num++] = p;
}
else
Console.WriteLine(" The cage is full ");
}
public T TakeOut()
{
if (num>0)
{
return array[--num];
}
else
{
Console.WriteLine(" There are no pets in the cage ");
return default(T);
}
}
}
} Generic methods :
Generic classes can have generic methods , Generic methods can also be found in common classes
grammar :
class Dog{
void DogIsHappy<T>(T target){}
}
Generic parameters can be used in parameter lists , It can also be used in the return value , It can also be in the method body
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog("jack");
dog.DogIsHappy<int>(7);
dog.DogIsHappy<Food>(new Food());
}
}
class Pet
{
private string name;
private int age;
public string Name { get => name; set => name = value; }
public int Age { get => age; set => age = value; }
public Pet(string name)
{
this.Name = name;
}
}
class Dog : Pet
{
public Dog(string name) : base(name) { }
public void DogIsHappy<T>(T target) {
Console.WriteLine(Name+" See "+target.ToString()+" Happy ");
}
}
class Food {
}
} If we have a need , You need to print out the passed parameter types and parameter values , We could write it this way :
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
ShowInt(7);
ShowString("ABC");
ShowDateTime(DateTime.Now);
}
/// <summary>
/// Print int value
/// Because when a method is declared , Fixed parameter type
/// </summary>
/// <param name="iParameter"></param>
public static void ShowInt(int iParameter)
{
Console.WriteLine("This is {0},parameter={1},type={2}",
typeof(Program).Name, iParameter.GetType().Name, iParameter);
}
/// <summary>
/// Print string value
/// </summary>
/// <param name="sParameter"></param>
public static void ShowString(string sParameter)
{
Console.WriteLine("This is {0},parameter={1},type={2}",
typeof(Program).Name, sParameter.GetType().Name, sParameter);
}
/// <summary>
/// Print DateTime value
/// </summary>
/// <param name="oParameter"></param>
public static void ShowDateTime(DateTime dtParameter)
{
Console.WriteLine("This is {0},parameter={1},type={2}",
typeof(Program).Name, dtParameter.GetType().Name, dtParameter);
}
}
} But we found that except for the incoming parameters , In fact, the treatment method is the same , So we changed it to Object type
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Show(7);
Show("ABC");
Show(DateTime.Now);
}
public static void Show(Object iParameter)
{
Console.WriteLine("This is {0},parameter={1},type={2}",
typeof(Program).Name, iParameter.GetType().Name, iParameter);
}
}
} such , We found the code simpler , The same effect can be achieved , But with Object type , It involves packing and unpacking , Packing and unpacking also involves the loss of program performance .
Microsoft 2.0 Introduce generics , It can solve this problem well .
The code is rewritten as follows :
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Show(7);
Show("ABC");
Show(DateTime.Now);
}
public static void Show<T>(T t)
{
Console.WriteLine("This is {0},parameter={1},type={2}",
typeof(Program).Name, t.GetType().Name, t);
}
}
} Generic interface : Definition is similar to generic class
Generic interface syntax :
interface IMyself<T>
{
T GetSome(T t);
}
Syntax for implementing generic interfaces :
class A : IMyself<A>
{
public A GetSome(A t) { return default(A); }
}
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
dog.study(new Sit());
}
}
interface ILearn<T> { // Define a generic interface for learning skills
void study(T t);
}
class Dog : Pet,ILearn<Sit> // Dogs inherit Pet class , And implement the skill generic interface
{
public void study(Sit t) {
Console.WriteLine(" Learn to sit down ");
}
}
class Sit { }
class Pet {
}
} Constraints of generics : Narrow the scope of generic types . We define generics , It can pass in value types , You can also pass in reference types , It's a wide range .
The type of constraint : Class name ( This class or a class that inherits this class ) class( Any class ) struct( Any value ) The interface name ( The interface type or any type that implements the interface ) new()( Classes with nonparametric common constructors )
Constraint overlay rule :A Master constraint ( Class name ,class,struct) There can only be 1 individual B Interface constraint ( Any number of ) C Construction constraints
Constraint grammar :
void Cage<T> where T:Pet,IclimbTree,new()
{}
This means passing in a generic parameter T, Yes T Constraint , It has to be Pet Class or Pet The derived class , Must be realized IclimbTree Interface , Must have a default constructor
class MyClassy<T, U> where T : class where U : struct
{}
If it's like above , Are multiple generic parameters ,where T That's right T Constraint is class( Only any class can be entered ) where U That's right U Constraint is struct( Only value types can be entered )
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog("jack");
//dog.DogIsHappy<int>(4); // Wrong incoming value type , because DogIsHappy Limit , Can only be Pet Class or inherited from Pet Class
dog.DogIsHappy<Dog>(new Dog("Lucy"));
}
}
class Pet {
private string name;
public string Name { get => name; set => name = value; }
public Pet(string name)
{
Name = name;
}
public void PrintName() {
Console.WriteLine(Name);
}
}
class Dog : Pet {
public Dog(string name) : base(name) { }
public void DogIsHappy<T>(T t) where T:Pet { // This constrains the incoming value to be only Pet Class or inheritance Pet Class
Console.WriteLine("happy because:"+t.Name);
}
}
} The first part of this article has a code :return default(T)
Now let's talk about default keyword
default Keyword can get the default value of this type .
int a=0; Equivalent to int a=default(int);
The reason why it is used default keyword , Because you need to know whether it is a value type or a reference type , Assign an initial value to an object .
class TestDefault<T>
{
public T foo()
{
T t = null; //???
return t;
}
}in fact , We don't know T Is it a reference type or a value type , The above code treats it as a reference type , But in case T It's a value type ? for example T yes int type , The line in the comment is meaningless , To solve this problem , We introduced default keyword .
class TestDefault<T>
{
public T foo()
{
return default(T);
}
} Reference resources :
C# Generic constraint
C# default(T) keyword
边栏推荐
- Linked list: orderly circular linked list
- Typical application of ACL
- In my ten years, every bit has become a landscape?
- 2022 qianle micro cloud technology learning task plan
- Vs Code modify default terminal_ Modify the default terminal opened by vs Code
- Coordinate location interface of wechat applet (II) map plug-in
- Linked lists: rearranging linked lists
- Ijkplayer source code - choose soft decoding or hard decoding
- On the limit problem of compound function
- Es and kibana deployment and setup
猜你喜欢

MySQL 8.0 installation free configuration method

Image classification system based on support vector machine (Matlab GUI interface version)

Typical application of ACL

Operating principle of JS core EventLoop
![HEAP[xxx.exe]: Invalid address specified to RtlValidateHeap( 0xxxxxx, 0x000xx)](/img/c9/884aa008a185a471dfe252c0756fc1.png)
HEAP[xxx.exe]: Invalid address specified to RtlValidateHeap( 0xxxxxx, 0x000xx)

Detailed explanation of data processing in machine learning (I) -- missing value processing (complete code attached)

2019 - sorting out the latest and most comprehensive IOS test questions (including framework and algorithm questions)

Vs 2022 new features_ What's new in visual studio2022

二叉树初始化代码

Radio design and implementation in IVI system
随机推荐
Keil removes annoying st link update tips
Professional database management software: Valentina Studio Pro for Mac
数字IC设计——FIFO的设计
【pytorch 记录】pytorch的变量parameter、buffer。self.register_buffer()、self.register_parameter()
MySQL index optimization (4)
Use of jstack
Linked list: adding numbers in the linked list
String: number of substring palindromes
The weight of the input and textarea components of the applet is higher than that of the fixed Z-index
【pytorch 記錄】pytorch的變量parameter、buffer。self.register_buffer()、self.register_parameter()
Exercise 8-3 rotate array right
PK of dotnet architecture
MySQL transactions and locks (V)
MySQL index bottom layer (I)
Mp4 playback
CDN single page reference of indexbar index column in vant framework cannot be displayed normally
如何挑选基金产品?什么样的基金是好基金?
JS merge multiple string arrays to maintain the original order and remove duplicates
Modify the color of El input, textarea and El checkbox when they are disabled
Vs Code modify default terminal_ Modify the default terminal opened by vs Code