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!
相关推荐
Python×CATIA工业智造3 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
我叫小白菜4 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
狐凄4 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
weixin_446122465 小时前
JAVA内存区域划分
java·开发语言·redis
悦悦子a啊5 小时前
Python之--基本知识
开发语言·前端·python
QuantumStack6 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
whoarethenext6 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
代码的奴隶(艾伦·耶格尔)7 小时前
后端快捷代码
java·开发语言
Jay_5157 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
路来了7 小时前
Python小工具之PDF合并
开发语言·windows·python