在我的 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/