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!
相关推荐
luj_176815 小时前
残熵算法实时化三大瓶颈突破
c语言·开发语言·网络·经验分享·算法
不听话坏16 小时前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
likeyi0716 小时前
require 和 import的区别
开发语言·前端
远离UE416 小时前
UE5 compute shader 原子加
开发语言·c++·ue5
C+-C资深大佬16 小时前
C++ 显式类型转换详解:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
KaMeidebaby17 小时前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
luj_176818 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
Mininglamp_271818 小时前
Claude Code 封禁中国开发者之后:本地 AI 编程工具的替代方案实测
开发语言·人工智能·windows·开源软件·ai-native
思麟呀19 小时前
C++17(三)if constexpr+折叠表达式
开发语言·c++
醉城夜风~19 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法