访问从数据库创建列表的类

本文关键字:列表 创建 数据库 访问 | 更新日期: 2023-09-27 17:58:13

我有下面的class,它基本上创建了一个类别列表(称为命令,我知道这很奇怪)

这是CommandDB.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlClient;
namespace TM_non_deploy
{
    public partial class CommandDB
    {
        private static string connectionString = "blah";
        public static List<Command> GetCommands()
        {
            List<Command> commandList = new List<Command>();
            DbConnection connection = new SqlConnection();
            SqlCommand cmd = (SqlCommand)connection.CreateCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_tm_commands";
            connection.ConnectionString = GetConnectionString();
            connection.Open();
            SqlDataReader reader = null;
            reader = cmd.ExecuteReader();
            Command command;
            while (reader.Read())
            {
                command = new Command();
                command.ID = reader.GetOrdinal("id");
                command.Name = reader["name"].ToString();
                commandList.Add(command);
            }
            reader.Close();
            connection.Close();
            return commandList;
        }
        private static string GetConnectionString()
        {
            return connectionString;
        }
    }
}

希望我的问题很简单,我如何在主页中访问这个列表,以便它调用函数并返回所有命令,以便我可以遍历它们?我以为它可能是类似List<CommandDB> commandList = new List<CommandDB.>GetCommands();的东西,但我真的没有通过msdn弄清楚它。

访问从数据库创建列表的类

此方法是静态的,因此应该像这样调用

 List<Command> commandList = CommandDB.GetCommands();
List<Command> myCommands = CommandDB.GetCommands();
foreach(Command com in myCommands)
{
    //Do stuff
}

我想这就是你要找的语法。

var commandList = CommandDB.GetCommands(); //implicit type detection by compiler

静态成员属于类型本身而不是特定对象

不能引用静态成员通过实例。相反,它是通过类型名称引用。

List<Command> commandList = CommandDB.GetCommands();

参考静态(C#参考)