我是C#新手,我正在努力学习(我最近一直在问一些关于C#的问题——我唯一的编程知识是Python、PHP和Javascript)。不管怎样,我在Web上找到了一些例子来说明如何在C语言中生成一个PACKLIST,并且我试图使用/修改它们来适应我现有的代码。结果出现了一个预期的类错误-但我正在创建一个类!这是我的代码:
private void PeerReview()
{
MySqlConnection connection;
string connStringName = "server=localhost;database=hourtracking;uid=username;password=password";
connection = new MySqlConnection(connStringName);
cmd.CommandText = "select name from peer_review_info where active_status=1";
cmd.Connection = connection;
connection.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["peerrevid"].ToString();
item.Value = sdr["peerrevid"].ToString();
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
chkPeerRev.Items.Add(item);
}
}
connection.Close();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.PeerReview();
}
}
最佳答案
你的右大括号太多了。应该是:
private void PeerReview()
{
MySqlConnection connection;
string connStringName =
"server=localhost;database=hourtracking;uid=username;password=password";
connection = new MySqlConnection(connStringName);
cmd.CommandText = "select name from peer_review_info where active_status=1";
cmd.Connection = connection;
connection.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["peerrevid"].ToString();
item.Value = sdr["peerrevid"].ToString();
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
chkPeerRev.Items.Add(item);
}
}
connection.Close();
}
实际上,它需要更多的更改;
connection
需要一个using
,并且很不清楚cmd
是在哪里定义的,但是它也需要一个using
并且不应该被共享(它应该被限定在这个方法的范围内)。我将重写为:private void PeerReview()
{
string connStringName = SomethingExternal.GetConnectionString();
using(var connection = new MySqlConnection(connStringName))
using(var cmd = connection.CreateCommand())
{
cmd.CommandText =
"select name from peer_review_info where active_status=1";
connection.Open();
using (var sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["peerrevid"].ToString();
item.Value = sdr["peerrevid"].ToString();
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
chkPeerRev.Items.Add(item);
}
}
}
}
关于c# - 获得CS1518:预期的类,委托(delegate),枚举,接口(interface)或结构错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12975155/