Extension Namespaces C#
In C#, extension namespaces are essentially used to organize extension methods. Extension methods were introduced in C# 3.0 as a feature that allows you to add new methods to existing types without modifying the original type, deriving from it, or using the decorator pattern.
- Extension methods must be defined in static classes
- The methods themselves must be static
- The first parameter is preceded by the
this
keyword, indicating the type being extended
using System;
using System.Collections.Generic;
using System.Linq;
// 定义包含扩展方法的命名空间
namespace ProjectUtils
{
// 扩展方法所在的静态类
public static class CollectionExtensions
{
// 为IEnumerable<T>添加一个扩展方法,用于安全地获取第一个元素
// 与FirstOrDefault不同,这个方法可以指定默认值
public static T GetFirstOrDefault<T>(this IEnumerable<T> source, T defaultValue)
{
// 检查集合是否为空
if (source == null || !source.Any())
return defaultValue;
return source.First();
}
}
}
namespace SampleApp
{
using ProjectUtils; // 导入包含扩展方法的命名空间
class Program
{
static void Main()
{
// 从数据库或API获取的用户列表
List<User> users = GetUsersFromDatabase();
// 尝试获取第一个管理员用户,如果没有则返回默认的系统管理员
User adminUser = users
.Where(u => u.IsAdmin)
.GetFirstOrDefault(new User { Name = "系统管理员", IsAdmin = true });
Console.WriteLine($"当前管理员: {adminUser.Name}");
}
// 模拟从数据库获取用户的方法
static List<User> GetUsersFromDatabase()
{
// 实际项目中,这里会连接数据库或调用API
return new List<User>
{
new User { Name = "张三", IsAdmin = false },
new User { Name = "李四", IsAdmin = false },
// 假设今天没有管理员登录,列表中没有管理员
};
}
}
class User
{
public string Name { get; set; }
public bool IsAdmin { get; set; }
}
}
查看其他文章