C# 泛型拓展内容
                           
天天向上
发布: 2025-04-20 18:56:54

原创
614 人浏览过

基于上篇讲到的C# 泛型(Generics),本篇重点针对如下4个内容做拓展讲解。

✅ 各种泛型设计模式模板代码
✅ 泛型 + 反射框架实践(比如 IOC 容器)
✅ 泛型委托函数式风格编程示例
✅ 泛型类和泛型方法设计的性能对比


✅ 1. 各种泛型设计模式模板代码


1.1 泛型单例模式(Generic Singleton)

public sealed class Singleton<T> where T : class, new()
{
    private static readonly Lazy<T> instance = new(() => new T());

    public static T Instance => instance.Value;
}

使用方式:

var logger = Singleton<Logger>.Instance;

1.2 泛型仓储模式(Generic Repository Pattern)

public interface IRepository<T> where T : class
{
    void Add(T entity);
    T GetById(int id);
    IEnumerable<T> GetAll();
}

public class InMemoryRepository<T> : IRepository<T> where T : class
{
    private readonly List<T> _store = new();

    public void Add(T entity) => _store.Add(entity);
    public T GetById(int id) => _store.ElementAtOrDefault(id);
    public IEnumerable<T> GetAll() => _store;
}

1.3 泛型工厂模式(Generic Factory)

public class Factory<T> where T : new()
{
    public T Create() => new T();
}

1.4 泛型服务定位器模式(Service Locator)

public class ServiceLocator
{
    private static readonly Dictionary<Type, object> services = new();

    public static void Register<T>(T instance) => services[typeof(T)] = instance;
    public static T Resolve<T>() => (T)services[typeof(T)];
}

2. 泛型 + 反射框架实践(IOC 容器)


简单 IoC 容器示例(带泛型 & 反射)

public interface IService { void Run(); }
public class MyService : IService { public void Run() => Console.WriteLine("Service Running"); }

public class SimpleContainer
{
    private readonly Dictionary<Type, Type> _types = new();

    public void Register<TInterface, TImplementation>() where TImplementation : TInterface
    {
        _types[typeof(TInterface)] = typeof(TImplementation);
    }

    public TInterface Resolve<TInterface>()
    {
        var type = _types[typeof(TInterface)];
        return (TInterface)Activator.CreateInstance(type);
    }
}

使用:

var container = new SimpleContainer();
container.Register<IService, MyService>();

var service = container.Resolve<IService>();
service.Run(); // 输出:Service Running

这就是一个 支持泛型、反射、自动实例化的 IoC 框架雏形


3. 泛型委托函数式风格编程示例


3.1 泛型方法 + Func 实现 Map 函数

public static class EnumerableExtensions
{
    public static IEnumerable<TResult> Map<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
    {
        foreach (var item in source)
            yield return selector(item);
    }
}

使用:

var nums = new List<int> { 1, 2, 3 };
var squares = nums.Map(n => n * n); // 1, 4, 9

3.2 泛型委托定义

public delegate TResult Transformer<TSource, TResult>(TSource input);

Transformer<int, string> intToStr = x => $"Num:{x}";

3.3 结合 LINQ 风格泛型

Func<int, bool> isEven = x => x % 2 == 0;
var result = Enumerable.Range(1, 10).Where(isEven);

4. 泛型类 vs 泛型方法性能对比


测试场景说明:

对比以下两种方式在执行大量数据操作时的性能差异:

  • 泛型方法:仅方法为泛型
  • 泛型类:类为泛型,方法为常规方法

泛型方法

public class Calculator
{
    public T Add<T>(T a, T b) where T : INumber<T>
    {
        return a + b;
    }
}

使用:

var calc = new Calculator();
int sum = calc.Add(10, 20);

泛型类

public class Calculator<T> where T : INumber<T>
{
    public T Add(T a, T b) => a + b;
}

使用:

var intCalc = new Calculator<int>();
int result = intCalc.Add(10, 20);

性能结论(基于 BenchmarkDotNet 测试):

  • 如果频繁调用:泛型类稍快(编译器优化得更彻底)
  • 如果调用分散,类型多样:泛型方法更灵活、占用更少内存

📘 推荐阅读 BenchmarkDotNet 使用:
https://benchmarkdotnet.org/


延伸阅读与源码参考

  • 🧩 泛型设计模式实战(C#)
    https://refactoring.guru/design-patterns/csharp
  • 🧩 BenchmarkDotNet(性能测试工具)
    https://github.com/dotnet/BenchmarkDotNet
  • 🧩 .NET 源码分析(泛型容器)
    https://github.com/dotnet/runtime

下篇文章将针对对该部分打包成项目结构,就可以直接在 Visual Studio 中运行调试。

发表回复 0

Your email address will not be published. Required fields are marked *