当前位置:网站首页>C # fine sorting knowledge points 10 generic (recommended Collection)
C # fine sorting knowledge points 10 generic (recommended Collection)
2022-07-25 15:27:00 【꧁ small ۣۖ Pigeon ۣۖ Puzi ۣۖ ิ꧂】
1. The concept of generics
Definition : Generics allow us to defer the specification of the data types of programming elements in a class or method , Until it's actually used in the program .( That is, generics are classes or methods that can work with any data type ) High cohesion in the module , Low coupling between modules .
The use of generics : When our class / Methods don't need to focus on what entities the caller passes ( Public base class tool class ), At this point, you can use generics .
Be careful :
Items in the collection are allowed to be object The value of the type , So you can store any type of value , There is no way to ensure that the values stored in the collection are of the same type , This causes an exception to occur during processing .
2. Null type
For variables of reference type , If it is not assigned , By default it is Null value , For variables of value type , If not assigned , The default value of an integer variable is 0.
But through 0 It is not very accurate to judge whether the variable is assigned . stay C# Language provides a generic type ( That is, empty type (System.Nullable)) To solve the problem that variables of value type are allowed to be Null The situation of .
Definition of nullable types :
System.Nullable<T> Variable name ;
type ? Variable name ;
Common methods for nullable types :
| Properties or methods | effect |
|---|---|
| HasValue | If the variable has a value; otherwise True, if null Then for False |
| Value | Return the real value stored in the nullable type variable , When HasValue by True You can use |
example :
class Program
{
static void Main(string[] args)
{
int? i = null;
double? d = 3.14;
if(i.HasValue)
{
Console.WriteLine("i The value of is {0}",i);
}
else
{
Console.WriteLine("i The value of is empty !");
}
if(d.HasValue)
{
Console.WriteLine("d The value of is {0}",d);
}
else
{
Console.WriteLine("d The value of is empty !")
}
}
}
3. Generic methods
stay C# In language, generic method refers to constraining the parameter types in the method through generics , It can also be understood as setting parameters for data types .
If there is no generics , The parameter types in each method are fixed , Can't change at will .
After using generics , The data type in the method has a specified generic type to constrain , That is, different types of parameters can be passed according to the provided generics .
Definition of generic methods :
Defining a generic method requires adding... Between the method name and the parameter list <>, And use in it T To represent the parameter type .
Be careful :
C# Only... Can be used in generic methods object Class has methods .
example :
class Program
{
static void Main(string[] args)
{
// take T Set to double type
GenericFunc<double>(3.3,4);
// take T Set to int type
GenericFunc<int>(3,4);
}
// Generic methods
private static void GenericFunc<T>(T a,T b)
{
Console.WriteLine(" Parameters 1:{0}, type :{1}, Parameters 2:{2}, type :{3}",a,a.GetType(),b,b.GetType());
}
}
4. Generic classes
C# The definition of generic classes in the language is similar to that of generic methods , Is to add... After the name of the generic class , Of course , You can also define multiple types , namely “<T1,T2,・・・>”.
Definition form :
class Class name <T1,T2,……>
{
// Class members
}
such , You can use... In the members of a class T1、T2 And so on .
example :
/// <summary>
/// Custom generic classes
/// </summary>
/// <typeparam name="T"></typeparam>
class MyTest<T>
{
private T[] items = new T[3];
private int index = 0;
// Add an item to the array
public void Add(T t)
{
if(index<3)
{
items[index] = t;
index++;
}
else{
Console.WriteLine(" The array is full !");
}
}
// Read all the items in the array
public void Show()
{
foreach(T t in items)
{
Console,WriteLine(t);
}
}
}
5. Data constraints in generics
Data constraints in generics can specify the scope of generic types .
If given T Data constraints of type struct, be T Can only accept struct Subclass types of , Otherwise, compilation error
example :
/// <summary>
/// Limits the range of types : Can only be IShape Implementation class of interface
/// </summary>
/// <typeparam name="T"></typeparam>
class MyTest<T> where T:Ishape
{
private T[] items = new T[3];
private int index = 0;
// Add an item to the array
public void Add(T t)
{
if(index<3)
{
items[index] = t;
index++;
}
else
{
Console.WriteLine(" The array is full !");
}
}
// Read all the items in the array
public void Show()
{
foreach(T t in items)
{
Console.WriteLine(t);
}
}
}
class Program
{
static void Main(string[] args)
{
MyTest<Rectangle> testObj = new MyTest<Rectangle>();
testObj.Add(new Rectangle(100,200));
testObj.Add(new Rectangle(50,50));
testObj.Show();
}
}
6. Generic set
C# Generic collections are the most common application of generics in languages , It is mainly used to constrain the elements stored in the collection .
Because any type of value can be stored in the collection , Data type conversion exceptions are often encountered when taking values , Therefore, it is recommended to use generic collections when defining collections .
Generic collections mainly use List and Dictionary<K,V> .
1.List< T > class
List Class is ArrayList The generic equivalent of class . This class uses an array whose size can be dynamically increased on demand IList Generic interface .
example :
class Program
{
static void Main(string[] args)
{
// Define generic collections
List<int> list = new List<int>();
// Put... Into the collection 3 A variable
list.Add(5);
list.Add(10);
list.Add(15);
// Traversing elements in a collection
foreach (var i in list)
{
Console.WriteLine(i);
}
}
}
2.Dictionary<K,V>
Dictionary<K,V> yes HashTable Corresponding generic collection , It stores data in a way similar to a hash table , Pass key / Value to save the element , And has all the characteristics of generics , Check type constraints at compile time , No type conversion is required when reading .
Use constraints :
From a set of keys (Key) To a set of values (Value) Mapping , Each addition is made by a Values and their associated keys
Any key must be unique
Key cannot be empty reference null, If the value is of reference type , Can be null
Key and Value It can be of any kind (string,int,class etc. )
example :
class Program
{
static void Main(string[] args)
{
Dictionary<int,Student> dictionary = new Dictionary<int,Student>();
Student stu1 = new Student(1," Xiao Zeng ",19);
Student stu2 = new Student(2," Xiaojia ",19);
Student stu3 = new Student(3," Xiaoyi ",19);
dictionary.Add(stu1.id,stu1);
dictionary.Add(stu2.id,stu2);
dictionary.Add(stu3.id,stu3);
Console.WriteLine(" Please enter the student number :");
int id = int.Parse(Console.ReadLine());
if(dictionary.ContainsKey(id))
{
Console.WriteLine(" Student information is :{0}", dictionary[id]);
}
else
{
Console.WriteLine(" The student number you are looking for is not !");
}
}
}
7.IComparable、IComparer Custom sort
stay C# The language provides IComparer and IComparable Interface compares object values in a collection , It is mainly used to sort the elements in the collection .
IComparer Interface is used to implement... In a separate class , Used to compare any two objects .
IComparable Interface is used to implement... In the class of the object to compare , You can compare any two objects .
A representation of generic interfaces is also provided in the comparator , namely IComparer and IComparable In the form of
1.IComparable< T > Interface
The custom types to compare need to inherit IComparable < T > Interface , And implement the following methods
| Method | effect |
|---|---|
| CompareTo(T obj) | Compare two object values , Return value less than 0 Represents that the current instance is smaller than the comparison instance , The return value is equal to 0 Means the two are equal , Return value greater than 0 Represents that the current instance is larger than the comparison instance |
If you need to sort the elements in the collection , Usually use CompareTo Method realization , Here is an example to demonstrate CompareTo Use of methods
class Student:IComparable<Student>
{
// Provides parametric construction methods , Assign values to properties
public Student(int id,string name,int age)
{
this.id = id;
this.name = name;
this.age = age;
}
// Student number
public int id{get;set;}
// full name
public string name{get;set;}
// Age
public int age{get;set;}
// rewrite Tostring Method
public override string ToString()
{
return id + ":" + name + ":" + age;
}
// Define the comparison method , Compare according to the students' age
public int CompareTo(Student other)
{
if(this.age<other.age)
{
return -1;
}
else if(this.age==other.age)
{
return 0;
}
else
{
return 1;
}
}
}
class Program
{
static void Main(string[] args)
{
// Create a generic list , The element type in the list is Student
List<Student> stuList = new List<Sudent>();
// Add three elements to the element
stuList.Add(new Student(3," Xiao Zeng ",19));
stuList.Add(new Student(1," Xiaojia ",19));
stuList.Add(new Student(2," Xiaoyi ",19));
// Traverse and output
foreach(var stu in stuList)
{
console.WriteLine(stu);
}
}
}
2、 IComparer < T > Interface
If you want to make custom types, you can use Sort Method to sort , Then you can customize a sort class , Realization IComparer < T > The following methods in the interface :
| Method | effect |
|---|---|
| Compare(T obj1,T obj2) | Compare two object values , Return value less than 0 Represents that the current instance is smaller than the comparison instance , The return value is equal to 0 Means the two are equal , Return value greater than 0 Represents that the current instance is larger than the comparison instance |
Create a new student type sorting class StudentComparer , Realization IComparer< Student > Interface .
example :
/// <summary>
/// Comparative , For two Student Object comparison
/// </summary>
class StudentComparer:IComparer<Student>
{
/// <summary>
/// Comparison method
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Comparer(Student x,Student y)
{
if(x.age<y.age)
{
return 1;
}
else if(x.age>y.age)
{
return -1;
}
else
{
return 0;
}
}
}
class Program
{
static void Main(string[] args)
{
// Create a generic list , The element type in the list is Student
List<Student> stuList = new List<Student>();
// Add three elements to the element
stuList.Add(new Student(3, " Zhang San ", 20));
stuList.Add(new Student(1, " Li Si ", 15));
stuList.Add(new Student(2, " Wang Wu ", 18));
// Traverse and output
foreach(var stu in stuList)
{
Console.WriteLine(stu);
}
Console.WriteLine(" After ordering :");
// Sort
stuList.Sort(new StudentComparer());
// Traverse and output
foreach(var stu in stuList)
{
Console.WriteLine(stu);
}
}
}
边栏推荐
- How to solve the login problem after the 30 day experience period of visual stuido2019
- How much memory can a program use at most?
- Find out what happened in the process of new
- ios 面试题
- MySQL installation and configuration super detailed tutorial and simple database and table building method
- ML - 语音 - 传统语音模型
- How to understand the maximum allowable number of errors per client connection of MySQL parameters in Seata?
- Instance Tunnel 使用
- Outline and box shadow to achieve the highlight effect of contour fillet
- Recommend 10 learning websites that can be called artifact
猜你喜欢
随机推荐
Qtime定义(手工废物利用简单好看)
p4552-差分
获取键盘按下的键位对应ask码
记一次Yarn Required executor memeory is above the max threshold(8192MB) of this cluster!
Node learning
redis淘汰策列
C#精挑整理知识要点9 集合2(建议收藏)
JVM parameter configuration details
HDU3873-有依赖的最短路(拓扑排序)
CGO is realy Cool!
MySQL heap table_ MySQL memory table heap Usage Summary - Ninth Five Year Plan small pang
VMware Workstation fails to start VMware authorization service when opening virtual machine
分布式原理 - 什么是分布式系统
MATLAB读取显示图像时数据格式转换原因
带你创建你的第一个C#程序(建议收藏)
ML - 自然语言处理 - 基础知识
Spark-SQL UDF函数
Spark judges that DF is empty
JVM-动态字节码技术详解
matlab--CVX优化工具包安装









