上一篇
在C#编程中,泛型委托和泛型接口是两个非常强大且常用的概念。它们不仅提升了代码的复用性,还增强了类型安全性。本教程将从基础讲起,帮助初学者理解并掌握如何在C#中使用和实现泛型委托与泛型接口。
在深入委托和接口之前,我们先简单回顾一下泛型(Generics)。泛型允许你在定义类、方法或委托时使用“占位符”类型(如 T),在实际使用时再指定具体类型。这样可以避免重复编写相似逻辑的代码。
泛型委托就是带有泛型参数的委托。C#内置了一些常用的泛型委托,比如 Action<T> 和 Func<T, TResult>。
// 使用 Func<T, TResult>:接收一个 int,返回 stringFunc<int, string> numberToString = x => $"数字是:{x}";Console.WriteLine(numberToString(42)); // 输出:数字是:42// 使用 Action<T>:接收一个 string,无返回值Action<string> printMessage = msg => Console.WriteLine(msg);printMessage("Hello, 泛型委托!"); 你也可以定义自己的泛型委托:
// 定义一个泛型委托:接收两个 T 类型参数,返回 boolpublic delegate bool Compare<T>(T x, T y);// 使用示例class Program{ static void Main() { Compare<int> isGreater = (a, b) => a > b; Console.WriteLine(isGreater(10, 5)); // True }} 泛型接口允许你在接口中使用泛型类型参数,使得实现类可以在编译时确定具体类型,从而提升类型安全性和性能。
public interface IRepository<T>{ void Add(T item); T GetById(int id); IEnumerable<T> GetAll();} public class Product{ public int Id { get; set; } public string Name { get; set; }}public class ProductRepository : IRepository<Product>{ private List<Product> _products = new List<Product>(); public void Add(Product item) { _products.Add(item); } public Product GetById(int id) { return _products.FirstOrDefault(p => p.Id == id); } public IEnumerable<Product> GetAll() { return _products; }}// 使用示例static void Main(){ var repo = new ProductRepository(); repo.Add(new Product { Id = 1, Name = "笔记本电脑" }); var product = repo.GetById(1); Console.WriteLine(product.Name); // 输出:笔记本电脑} 在实际开发中,泛型委托常与泛型接口配合使用,例如在仓储模式中通过委托实现自定义查询逻辑:
public interface IRepository<T>{ IEnumerable<T> Find(Func<T, bool> predicate);}public class ProductRepository : IRepository<Product>{ private List<Product> _products = new List<Product>(); public IEnumerable<Product> Find(Func<Product, bool> predicate) { return _products.Where(predicate); } // 其他方法...}// 使用var laptops = repo.Find(p => p.Name.Contains("笔记本")); 通过本教程,你已经学会了:
掌握这些知识,将极大提升你在C#开发中的代码质量与效率。希望这篇C#教程对你有所帮助!
关键词:C#泛型委托、泛型接口、C#教程、委托与接口实现
本文由主机测评网于2025-12-24发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/20251212082.html