c# - Asp.NET 返回空 List<Object> C#

标签 c# list collections null return

在我的 ASP.NET 经典 WebForms 应用程序中,我有一个类返回一个 Role 对象列表,我用它来映射数据库中用户的角色。

我写了这个静态类:

public static class RoleHelper
{
    public static List<RoleValue> getRoles()
    {
        List<RoleValue> myroles = null;
        string connectionString = ConfigurationManager.ConnectionStrings["SQLConnStr"].ConnectionString;
        if (!string.IsNullOrWhiteSpace(connectionString))
        {
            using (SqlConnection dbconn = new SqlConnection(connectionString))
            {
                dbconn.Open();
                SqlDataAdapter cmd = new SqlDataAdapter(" SELECT groupID,Name FROM Gruppi", dbconn);
                cmd.SelectCommand.CommandType = CommandType.Text;
                DataSet ds = new DataSet();
                cmd.Fill(ds);
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    myroles = new List<RoleValue>();

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        RoleValue myrole = new RoleValue();
                        myrole.roleID = (int)row["groupID"]; ;
                        myrole.roleName = (string)row["Name"]; ;
                        myroles.Add(myrole);
                    }
                }
                dbconn.Close();
            }
        }
        return myroles;
    }
}

一开始我写道:

List(RoleValue) myroles = null; 

这是错误的吗?

在调用函数中,我检查 if (rolesList.Count > 0) 但我应该检查 if(!rolesList is null) 但不允许使用 null列表?

最佳答案

将列表初始化为null并没有错,但这种方式使用更广泛:

List<RoleValue> myroles = new List<RoleValue>();

然后您将返回列表,调用者将检查列表的长度以查看是否为空,如下所示:

List<RoleValue> listOfRoles = getRoles();

if(listOfRoles.Count == 0)
{
    // Report message to user if having no roles is worthy of a notification
}

null 相比,返回列表实例的优点是用户将执行的大多数操作无需检查 null 即可运行,例如数据绑定(bind)和迭代列表。

关于c# - Asp.NET 返回空 List<Object> C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18190353/

相关文章:

c# - WPF : How to not block the GUI thread in HwndHost. BuildWindowCore 中的死锁?

list - 是否有与 Perl 的转变等效的 Tcl?

java - 为什么这个对象在此 ArrayList 中显示为 "unknown class"?

java - 如何根据谓词有效地将对象从一个 Java 集合传输到另一个集合?

javascript - 从 Meteor 集合文档中检索特定字段到 JS 文件中并剥离 HTML 标签

c# - Firefox 忽略 Response.ContentType

c# - 如何在 C# 中使用参数执行 Java 应用程序

c# - 通过文本框从 Datagridview 进行行更新

list - 如何通过列表理解计算频率?

java - Collectors.toMap() 中映射的默认值