当前位置:网站首页>C [advanced part] C generic [need to be further supplemented: generic interfaces and instances of generic events]
C [advanced part] C generic [need to be further supplemented: generic interfaces and instances of generic events]
2022-06-30 03:21:00 【Tomorrow is like noon】
C#【 Advanced 】 C# Generic (Generic)
Preface
Generic (Generic) Allow you to Delay writing specifications for data types of programming elements in a class or method , Until it's actually used in the program . let me put it another way , Generics allow you to Write a class or method that can work with any data type .
You can Write the specification of a class or method through alternative parameters of a data type . When the compiler encounters a function call of a class's constructor or method , It generates code to handle the specified data type . The following simple example will help you understand this concept :
using System;
using System.Collections.Generic;
namespace GenericApplication
{
public class MyGenericArray<T>
{
private T[] array;
public MyGenericArray(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;
}
}
class Tester
{
static void Main(string[] args)
{
// Declare an integer array
MyGenericArray<int> intArray = new MyGenericArray<int>(5);
// Set the value
for (int c = 0; c < 5; c++)
{
intArray.setItem(c, c*5);
}
// Get value
for (int c = 0; c < 5; c++)
{
Console.Write(intArray.getItem(c) + " ");
}
Console.WriteLine();
// Declare a character array
MyGenericArray<char> charArray = new MyGenericArray<char>(5);
// Set the value
for (int c = 0; c < 5; c++)
{
charArray.setItem(c, (char)(c+97));
}
// Get value
for (int c = 0; c < 5; c++)
{
Console.Write(charArray.getItem(c) + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
Running results :
0 5 10 15 20
a b c d e
Generic (Generic) Characteristics of
Using generics is a technique to enhance program functionality , Specifically in the following aspects :
- It helps you maximize reuse of code 、 Protect types of security and improve performance .
- You can create generic collection classes ..NET The class library is in the framework System.Collections.Generic The namespace contains some new generic collection classes . You can use these generic collection classes instead of System.Collections Set class in .
- You can create your own generic interfaces 、 Generic classes 、 Generic methods 、 Generic events and generic delegates .
- You can constrain generic classes to access methods of specific data types .
- Information about the types used in generic data types can be obtained at run time by using reflection .
Generic methods
In the example above , We have used generic classes , We can declare generic methods through type parameters . The following procedure illustrates this concept :
using System;
using System.Collections.Generic;
namespace GenericMethodAppl
{
class Program
{
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';
// Display values before switching
Console.WriteLine("Int values before calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values before calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
// call swap
Swap<int>(ref a, ref b);
Swap<char>(ref c, ref d);
// Display the value after the exchange
Console.WriteLine("Int values after calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values after calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Console.ReadKey();
}
}
}
Running results :
Int values before calling swap:
a = 10, b = 20
Char values before calling swap:
c = I, d = V
Int values after calling swap:
a = 20, b = 10
Char values after calling swap:
c = V, d = I
Commissioned by the generic
You can define generic delegates through type parameters . for example :
delegate T NumberChanger<T>(T n);
The following example demonstrates the use of delegates :
using System;
using System.Collections.Generic;
delegate T NumberChanger<T>(T n);
namespace GenericDelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
// Create a delegate instance
NumberChanger<int> nc1 = new NumberChanger<int>(AddNum);
NumberChanger<int> nc2 = new NumberChanger<int>(MultNum);
// Use a delegate object to call a method
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed , It will produce the following results :
Value of Num: 35
Value of Num: 175
summary
边栏推荐
- Use compose to realize the effect of selecting movie seats by panning tickets
- mysql 主从数据库同步失败的原因
- mysqldump原理
- Reasons for MySQL master-slave database synchronization failure
- 一篇文章带你入门vim
- Servlet面试题
- Servlet interview questions
- QT中foreach的使用
- Global and Chinese market of bulk acoustic wave devices 2022-2028: Research Report on technology, participants, trends, market size and share
- 4-4 beauty ranking (10 points)
猜你喜欢

1152_ Makefile learning_ Pattern matching rules

golang bilibili直播彈幕姬

X书6.97版本shield-unidbg调用方式

1151_ Makefile learning_ Static matching pattern rules in makefile

The broadcast module code runs normally in autojs4.1.1, but an error is reported in pro7.0 (not resolved)

Use compose to realize the effect of selecting movie seats by panning tickets

How to realize remote collaborative office, keep this strategy!

广播模块代码在autojs4.1.1版本运行正常,但在pro7.0版本上运行报错(未解决)

Realization of BFS in C language by storing adjacency matrix of graph

X Book 6.89 shield unidbg calling method
随机推荐
Global and Chinese market for sensor screwdrivers 2022-2028: Research Report on technology, participants, trends, market size and share
Use of custom MVC
What are outer chain and inner chain?
prompt learning 一个空格引发的血案
1150_ Makefile learning_ Duplicate name target processing in makefile
HOOK Native API
Add a custom button to jvxetable
【微信小程序】条件渲染 列表渲染 原来这样用?
Servlet interview questions
图的邻接矩阵存储 C语言实现BFS
Formal and actual parameters, value passing and address passing
Comparable和Comparator的区别
Neo4j--- performance optimization
A GPU approach to particle physics
专升本高数(四)
1151_ Makefile learning_ Static matching pattern rules in makefile
JS conversion of letters and numbers
Shell counts all strings before the last occurrence of a string
广播模块代码在autojs4.1.1版本运行正常,但在pro7.0版本上运行报错(未解决)
zabbix 触发器详解