c#泛型学习

使用泛型的优点:使用泛型的好处包括类型安全、代码重用和性能优化。

在C#中,泛型是一种强大的工具,它允许你在编写类、接口、方法和委托时定义类型参数。这些类型参数在实例化泛型类型或调用泛型方法时被具体的类型所替代。

1. 泛型类

泛型类允许定义一个类,其成员可以操作任意类型的数据。

csharp 复制代码
public class GenericBox<T>
{
    private T value;
 
    public void SetValue(T value)
    {
        this.value = value;
    }
 
    public T GetValue()
    {
        return value;
    }
}
csharp 复制代码
// 使用泛型类
var intBox = new GenericBox<int>();
intBox.SetValue(123);
Console.WriteLine(intBox.GetValue());  // 输出: 123
 
var stringBox = new GenericBox<string>();
stringBox.SetValue("Hello");
Console.WriteLine(stringBox.GetValue());  // 输出: Hello

2. 泛型方法

泛型方法允许在方法签名中定义类型参数。

csharp 复制代码
public static class GenericMethods
{
    public static void PrintArray<T>(T[] array)
    {
        foreach (var item in array)
        {
            Console.WriteLine(item);
        }
    }
}
csharp 复制代码
// 使用泛型方法
int[] intArray = { 1, 2, 3, 4, 5 };
GenericMethods.PrintArray(intArray);  // 输出: 1 2 3 4 5
 
string[] stringArray = { "a", "b", "c" };
GenericMethods.PrintArray(stringArray);  // 输出: a b c

3. 泛型接口

泛型接口允许定义一个接口,成员可以操作任意类型的数据。

csharp 复制代码
public interface IGenericRepository<T>
{
    void Add(T item);
    T Get(int id);
}
 
public class StringRepository : IGenericRepository<string>
{
    private List<string> items = new List<string>();
 
    public void Add(string item)
    {
        items.Add(item);
    }
 
    public string Get(int id)
    {
        return items[id];
    }
}
csharp 复制代码
// 使用泛型接口
var repo = new StringRepository();
repo.Add("Item1");
repo.Add("Item2");
Console.WriteLine(repo.Get(0));  // 输出: Item1

4. 泛型约束

泛型约束允许指定泛型类型参数必须满足的条件。常见的约束包括 where T : struct(T是值类型)where T : class(T是引用类型)where T : new()(T有一个无参数的构造函数)where T : IComparable<T>(T实现了IComparable<T>接口)等。

csharp 复制代码
public class GenericList<T> where T : new()
{
    private List<T> items = new List<T>();
 
    public void Add()
    {
        items.Add(new T());
    }
 
    public void PrintAll()
    {
        foreach (var item in items)
        {
            Console.WriteLine(item);
        }
    }
}
 
csharp 复制代码
// 使用带约束的泛型类
var list = new GenericList<Person>();
list.Add();  // 添加一个新的Person对象, Person中必须有一个无参数的构造函数
list.Add();
list.PrintAll();
 
public class Person
{
    public string Name { get; set; }
 
    public Person()
    {
        Name = "Unknown";
    }
 
    public override string ToString()
    {
        return Name;
    }
}

5. 泛型委托和事件

可以使用泛型来定义委托和事件。

csharp 复制代码
// 泛型委托
public delegate T GenericFunc<T>(T arg);
 
// 使用泛型委托
GenericFunc<int> square = x => x * x;
Console.WriteLine(square(5));  // 输出: 25
 
// 泛型事件
public delegate void GenericEventHandler<T>(object sender, T e);
 
public class GenericEventSource<T>
{
    public event GenericEventHandler<T> OnEvent;
 
    protected virtual void RaiseEvent(T e)
    {
        OnEvent?.Invoke(this, e);
    }
}
csharp 复制代码
// 使用泛型事件
var source = new GenericEventSource<string>();
source.OnEvent += (sender, e) => Console.WriteLine($"Event received: {e}");
source.RaiseEvent("Hello, World!");  // 输出: Event received: Hello, World!
相关推荐
消费知多少几秒前
解析勤策签约大西洋焊接费用核销实践案例
开发语言·c#
CSDN_RTKLIB2 分钟前
HashSet、Dictionary
c#
曹牧24 分钟前
C#与Java后台交互
java·windows·microsoft·c#
LabVIEW开发32 分钟前
LabVIEW按段拆分TDMS文件的格式边界与重构
开发语言·数据库·重构·labview·labview知识·labview功能·labview程序
asdzx6744 分钟前
使用 Python 为 Excel 添加各类数据验证规则
开发语言·python·excel
Romantic_love_44 分钟前
理解USART真实收发过程
开发语言·stm32·单片机·学习
撩得Android一次心动1 小时前
Kotlin 语言【知识点整理3】
java·开发语言·笔记·学习·kotlin
2601_966949651 小时前
如何利用 1 分钟 K 线在 14:50 精准捕捉尾盘异动?Python 量化实战:1 分钟 K 线 + 全市场扫描
开发语言·人工智能·python·量化·quantdash·量化数据源
CarIise1 小时前
JavaScript基础语法与DOM操作实战课堂笔记
开发语言·javascript·笔记
林森lsjs1 小时前
零基础吃透二叉树:定义、遍历与高频算法 —数据结构柒
java·开发语言·数据结构·算法·二叉树