[英]Use of unassigned local variable
...
...
...
try
{
string Tags_collect;
SqlDataReader Data1 = cmd.ExecuteReader();
Data1.Read();
lbl_q_title.Text = Data1["subject"].ToString();
Data1.NextResult();
while (Data1.Read())
{
Tags_collect = Data1.GetString(0);
Tags_collect= Tags_collect+ Tags_collect;
}
lbl_tags.Text = Tags_collect;
.....
....
....
not sure why i get this error what do i miss? 不知道为什么我会收到此错误我想念什么?
The first time you assign to Tags_collect
is inside the while (Data1.Read())
loop, which is not guaranteed to ever execute. 第一次分配给
Tags_collect
时间是在while (Data1.Read())
循环内,不能保证永远执行该循环。
Fix this by initializing the variable when it's declared: 通过在声明变量时初始化变量来解决此问题:
string Tags_collect = string.Empty;
Better yet, use a StringBuilder
instead of relying on repeated concatenations: 更好的是,使用
StringBuilder
而不是依赖于重复的串联:
StringBuilder tags = new StringBuilder();
// ...
while (Data1.Read())
{
string tag = Data1.GetString(0);
sb.Append(tag);
sb.Append(","); // Separator
}
lbl_tags.Text = tags.ToString();
Concatenating a string to itself in a loop is very inefficient because strings are immutable, so each concatenation creates a brand-new instance. 由于字符串是不可变的,因此在一个循环中将字符串连接到自身效率很低,因此每个串联都会创建一个全新的实例。 Using a
StringBuilder
prevents this by using a single buffer. 使用
StringBuilder
可以通过使用单个缓冲区来防止这种情况。
因为如果Data1.Read()
在开始时返回false,则不会分配Tags_collect
。
The compiler has to take into account the possibility that Data1.Read()
in the while loop condition may never return true. 编译器必须考虑while循环条件下
Data1.Read()
永远不会返回true的可能性。 If that happens then Tags_collect is never initialized, hence the error. 如果发生这种情况,那么Tags_collect将永远不会初始化,因此会出错。
you need to set your reader in a while loop like this small sample: 您需要像以下小样本一样在while循环中设置阅读器:
SqlDataReader reader = command.ExecuteReader(); SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
尝试这个:
string Tags_collect=string.empty;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.