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!
相关推荐
guygg884 分钟前
人行走作用下板的振动响应 MATLAB 仿真
开发语言·matlab
小二·26 分钟前
Next.js 15 全栈开发实战
开发语言·javascript·ecmascript
fox_lht28 分钟前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
java1234_小锋1 小时前
LangChain4j 开发Java Agent智能体- 多模态支持
java·开发语言·langchain4j
凡人叶枫1 小时前
Effective C++ 条款23:宁以 non-member、non-friend 替换 member 函数
linux·开发语言·c++·嵌入式开发
张忠琳1 小时前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
盈建云系统1 小时前
B2B产品展示网站怎么做?从产品目录到询盘表单,企业获客页面搭建流程
开发语言·网站搭建·开发网站
不会C语言的男孩1 小时前
Linux 系统编程 · 第 4 章:文件属性与元数据
linux·c语言·开发语言
kernelcraft1 小时前
Boto3:Python 操作 AWS 的官方 SDK
开发语言·python·其他·aws
D3bugRealm1 小时前
cryptography:Python 开发者的加密标准库
开发语言·python·其他