gpt4 book ai didi

c# - 使用未分配的局部变量 - SQL + C#

转载 作者:行者123 更新时间:2023-11-29 08:21:17 24 4
gpt4 key购买 nike

我试图让服务器从 SQL 数据库读取 int 'rank',但是我收到“使用未分配的局部变量”,因为它不会读取 'rank',直到它应该被设置一个 while 语句,但是我无法将其移出,因为它在进入 try 和 catch 之前不会执行 SQL 查询。

具体在这里:

using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
rank = rdr.GetInt32("rank");
}

完整代码:

class Ban : ICommand
{
public string Command { get { return "ban"; } }
public int RequiredRank { get { return 3; } }

public void Execute(Player player, string[] args)
{
int rank;
string name = "'" + args[0] + "'";
if (args.Length == 0)
{
player.SendHelp("Usage: /ban <username>");
}
try
{
using (Database dbx = new Database())
{
var cmd = dbx.CreateQuery();
cmd.CommandText = "SELECT rank FROM accounts where name=@name";
cmd.Parameters.AddWithValue("@name", name);
cmd.ExecuteNonQuery();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
rank = rdr.GetInt32("rank");
}
Console.Write("{0} ({1}) tried to ban {2}({3})", player.Name, player.Client.Account.Rank, name, rank);
if (rank < player.Client.Account.Rank)
{
var cmda = dbx.CreateQuery();
cmda.CommandText = "UPDATE accounts SET banned=1, rank=0 WHERE name=@name";
cmda.Parameters.AddWithValue("@name", args[0]);
if (cmda.ExecuteNonQuery() == 0)
{
player.SendInfo("Could not ban");
}
else
{
foreach (var i in player.Owner.Players)
{
if (i.Value.nName.ToLower() == args[0].ToLower().Trim())
{
i.Value.Client.Disconnect();
player.SendInfo("Account successfully Banned");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Out.WriteLine(args[0] + " was Banned.");
Console.ForegroundColor = ConsoleColor.White;
}
}
}
}
else if (rank >= player.Client.Account.Rank)
player.SendInfo("Could not ban");
}
}
catch
{
player.SendInfo("Could not ban");
}
}
}

最佳答案

编译器警告您,该变量在您使用时可能尚未分配。

using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
rank = rdr.GetInt32("rank");
}

rdr.Read() 可能会立即返回 false,并且不会发生排名分配。

在声明的地方初始化rank,即:intrank = 0;

关于c# - 使用未分配的局部变量 - SQL + C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com