温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#中泛型如何使用

发布时间:2025-02-15 22:20:40 阅读:88 作者:小樊 栏目:编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,泛型是一种强大的特性,它允许你在编译时定义可重用的代码组件,这些组件可以适用于多种数据类型。使用泛型可以提高代码的灵活性、可读性和性能,同时减少代码重复。

以下是在C#中使用泛型的基本步骤:

1. 定义泛型类、接口或方法

泛型类

public class GenericClass<T>
{
    public T Data { get; set; }

    public void PrintData()
    {
        Console.WriteLine(Data);
    }
}

泛型接口

public interface IRepository<T>
{
    void Add(T item);
    T GetById(int id);
}

泛型方法

public T GenericMethod<T>(T param)
{
    return param;
}

2. 使用泛型类、接口或方法

使用泛型类

GenericClass<int> intClass = new GenericClass<int>();
intClass.Data = 10;
intClass.PrintData(); // 输出: 10

GenericClass<string> stringClass = new GenericClass<string>();
stringClass.Data = "Hello, World!";
stringClass.PrintData(); // 输出: Hello, World!

使用泛型接口

public class Repository<T> : IRepository<T>
{
    private List<T> _items = new List<T>();

    public void Add(T item)
    {
        _items.Add(item);
    }

    public T GetById(int id)
    {
        // 简单示例,实际应用中可能需要更复杂的逻辑
        return _items.FirstOrDefault(i => i.GetHashCode() == id);
    }
}

IRepository<int> intRepo = new Repository<int>();
intRepo.Add(1);
intRepo.Add(2);
Console.WriteLine(intRepo.GetById(1)); // 输出: 1

使用泛型方法

int result = GenericMethod<int>(5); // 输出: 5
string strResult = GenericMethod<string>("Hello"); // 输出: Hello

3. 约束泛型类型参数

你可以使用约束来限制泛型类型参数的类型。常见的约束包括:

  • where T : class:T必须是引用类型。
  • where T : struct:T必须是值类型。
  • where T : new():T必须有一个无参数的构造函数。
  • where T : BaseClass:T必须是BaseClass的派生类。
  • where T : IInterface:T必须实现IInterface接口。

示例:带约束的泛型类

public class GenericClassWithConstraint<T> where T : new()
{
    public T CreateInstance()
    {
        return new T();
    }
}

GenericClassWithConstraint<MyClass> myClassInstance = new GenericClassWithConstraint<MyClass>();
MyClass obj = myClassInstance.CreateInstance();

4. 泛型集合

C#标准库提供了许多泛型集合类,如List<T>Dictionary<TKey, TValue>等。

示例:使用泛型集合

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Dictionary<string, int> ageMap = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 25 }
};

foreach (var pair in ageMap)
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}

通过这些步骤,你可以在C#中有效地使用泛型来编写灵活且可重用的代码。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×