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!
相关推荐
oioihoii3 分钟前
C++网络编程:从Socket混乱到优雅Reactor的蜕变之路
开发语言·网络·c++
笙年29 分钟前
JavaScript Promise,包括构造函数、对象方法和类方法
开发语言·javascript·ecmascript
神仙别闹37 分钟前
基于C++实现(控制台)应用递推法完成经典型算法的应用
开发语言·c++·算法
kk哥88991 小时前
inout参数传递机制的底层原理是什么?
java·开发语言
listhi5202 小时前
基于改进SET的时频分析MATLAB实现
开发语言·算法·matlab
友友马2 小时前
『QT』事件处理机制详解 (一)
开发语言·qt
孤独斗士2 小时前
maven的pom文件总结
java·开发语言
confiself2 小时前
通义灵码分析ms-swift框架中CHORD算法实现
开发语言·算法·swift
1024小神3 小时前
在 Swift 中,self. 的使用遵循明确的规则
开发语言·ios·swift
Swift社区3 小时前
Swift 类型系统升级:当协议遇上不可拷贝的类型
开发语言·ios·swift