C# 泛型实战项目结构模板
以下是标准化的 C# 泛型实战项目结构模板,你可以直接在 Visual Studio 中创建一个 .NET Console App 项目,并将以下结构与代码粘贴到相应文件中。
项目结构目录
/GenericApp
│
├── Program.cs
├── Services/
│ ├── IService.cs
│ └── MyService.cs
├── Infrastructure/
│ ├── SimpleContainer.cs
│ ├── Singleton.cs
│ └── Factory.cs
├── Extensions/
│ └── EnumerableExtensions.cs
1. Program.cs
using GenericApp.Infrastructure;
using GenericApp.Services;
using GenericApp.Extensions;
namespace GenericApp
{
class Program
{
static void Main()
{
// IoC 容器注册
var container = new SimpleContainer();
container.Register<IService, MyService>();
var service = container.Resolve<IService>();
service.Run();
// 泛型单例使用
var logger = Singleton<Logger>.Instance;
logger.Log("单例日志测试");
// 泛型工厂使用
var factory = new Factory<MyService>();
var serviceFromFactory = factory.Create();
serviceFromFactory.Run();
// 泛型扩展方法使用
var numbers = new[] { 1, 2, 3, 4 };
var squares = numbers.Map(n => n * n);
Console.WriteLine(string.Join(", ", squares));
}
}
public class Logger
{
public void Log(string message) => Console.WriteLine($"[LOG] {message}");
}
}
2. Services/IService.cs
namespace GenericApp.Services
{
public interface IService
{
void Run();
}
}
3. Services/MyService.cs
namespace GenericApp.Services
{
public class MyService : IService
{
public void Run()
{
Console.WriteLine("MyService 正在运行...");
}
}
}
4. Infrastructure/SimpleContainer.cs
using System;
using System.Collections.Generic;
namespace GenericApp.Infrastructure
{
public class SimpleContainer
{
private readonly Dictionary<Type, Type> _registrations = new();
public void Register<TInterface, TImplementation>() where TImplementation : TInterface
{
_registrations[typeof(TInterface)] = typeof(TImplementation);
}
public TInterface Resolve<TInterface>()
{
var implType = _registrations[typeof(TInterface)];
return (TInterface)Activator.CreateInstance(implType)!;
}
}
}
5. Infrastructure/Singleton.cs
using System;
namespace GenericApp.Infrastructure
{
public sealed class Singleton<T> where T : class, new()
{
private static readonly Lazy<T> _instance = new(() => new T());
public static T Instance => _instance.Value;
}
}
6. Infrastructure/Factory.cs
namespace GenericApp.Infrastructure
{
public class Factory<T> where T : new()
{
public T Create() => new T();
}
}
7. Extensions/EnumerableExtensions.cs
using System;
using System.Collections.Generic;
namespace GenericApp.Extensions
{
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);
}
}
}
编译方式
你只需要:
- 在 Visual Studio 或 Rider 中创建一个新
.NET 6 或 7的 Console App 项目 - 按上面结构新建文件并拷贝代码进去
- 编译运行,观察控制台输出效果
更多详细内容请关注其他相关文章!