C#重构代码的8种基本方法

C#重构代码的8种基本方法

重构是指在不改变代码行为的情况下,提高代码的可读性、可维护性和效率的过程。本文介绍8种重构C#代码的基本方法。

  1. 删除冗余代码
    重构前

    List<int> userIds = new List<int>();
    userIds.AddRange(output.Select(s => s.UserId).Distinct().ToList());
    userIds = userIds.Distinct().ToList();

    重构后

    var userIds = output.Select(s => s.UserId).Distinct().ToList();
  2. 使用LINQ替代循环
    重构前

    List<int> evenNumbers = new List<int>();
    foreach (var num in numbers) {
    if (num % 2 == 0) {
        evenNumbers.Add(num);
    }
    }

    重构后

    var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
  3. 避免重复代码(封装方法)
    重构前

    var segmentIDs = output.Select(s => s.SegmentID).Distinct().ToList();
    if (segmentIDs.Any()) {
    segments = db.CheckCode
        .Where(c => segmentIDs.Contains(c.CheckCodeID))
        .ToList();
    }

    重构后

    List<int> GetDistinctIDs<T>(IEnumerable<T> source, Func<T, int?> selector) =>
    source.Select(selector).Where(id => id.HasValue).Select(id => id.Value).Distinct().ToList();
  4. 使用空合并和三元运算符
    重构前

    string name;
    if (user != null && user.Name != null) {
    name = user.Name;
    } else {
    name = "Unknown";
    }

    重构后

    string name = user?.Name ?? "Unknown";
  5. 使用var提升可读性
    重构前

    List<int> numbers = new List<int> { 1, 2, 3, 4 };

    重构后

    var numbers = new List<int> { 1, 2, 3, 4 };
  6. 避免嵌套的if语句
    重构前

    if (user != null) {
    if (user.Age > 18) {
        Console.WriteLine("Adult");
    }
    }

    重构后

    if (user == null) return;
    if (user.Age <= 18) return;
    Console.WriteLine("Adult");
  7. 使用字符串插值
    重构前

    string message = string.Format("Hello, {0}! You have {1} messages.", name, count);

    重构后

    string message = $"Hello, {name}! You have {count} messages.";
  8. 使用async/await提升性能
    重构前

    public List<User> GetUsers() {
    return db.Users.ToList();
    }

    重构后

    public async Task<List<User>> GetUsersAsync() {
    return await db.Users.ToListAsync();
    }

总结
在代码重构时,应该始终遵循以下原则:

可读性:代码应当易于理解。
可维护性:让未来的开发者能够轻松修改代码。
性能:避免不必要的计算和冗余操作。
DRY(不要重复自己):提取可复用的逻辑到方法中,提高代码复用性。
译文:csharp.com/article/learn-c-sharp-refactor-code

https://mp.weixin.qq.com/s?__biz=MzI2NDE1MDE1MQ==&mid=2650862370&idx=1&sn=d5a8c6b375dc6a9b0f122ffe65593a72&chksm=f1455ecac632d7dc3fd7e2fe0daaefd16ea2ca25f1e7782b3c6527e0af055b22d3a5f33d7818&cur_album_id=1924294891300290563&scene=190#rd

Leave a Reply

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