c# - 如何优化分配的真实状态

标签 c# .net

我有这个代码:

// Image one : first row
user = ReturnUser(pictureBoxUpOne);
if (user != null)
{
     usersFirstRow.Add(user);
     user = null;
}
// Image two : first row
user = ReturnUser(pictureBoxUpTwo);
if (user != null)
{
     usersFirstRow.Add(user);
     user = null;
}

我对每张图片都重复了几次。所以我想知道有什么方法可以避免做以下事情:

if (user != null)

和我在同一行

usersFirstRow.Add(user); 

仅当它不为 null 时才添加它,例如优化的 ifs

最佳答案

我会将代码重构为接收图片框列表的函数。

private void MyMethod(List<PictureBox> pictureBoxes)
{
    foreach (var pictureBox in pictureBoxes)
    {
        var user = ReturnUser(pictureBox);
        if (user != null)
        {
             usersFirstRow.Add(user);
             // This line not needed: user = null; 
        }
    }
}

List<PictureBox> pictureBoxes = 
    new List<PictureBox>() { pictureBoxUpOne, pictureBoxUpTwo }

MyMethod(pictureBoxes);

关于c# - 如何优化分配的真实状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14231825/

相关文章:

c# - 在 C# 中,是否可以将两个不同的类作为返回类型从一层传递到另一层?

C# 传递内联代码时遇到问题

asp.net - 为什么 HttpUtility.UrlPathEncode 标记为 "do not use"?

c# - Sharepoint 2010。搜索

c# - 验证器和服务与外部 API 调用的分离

c# - View 模型继承和重复模型引用

.net - 在数据库中存储 IP 地址的最佳方式

c# - 如何根据元素的位置使用 Linq 重命名数据?

c# - FileOptions.Asynchronous 导致 FileStream.BeginRead 阻塞

c# - 使用需要 SSL 证书的 Web 服务