这是它给出的错误,我的商业代码很好以及存储过程,没有“strCity”变量一切正常,但是我添加这个添加的那一刻,正在给我带来麻烦
txtCityName.Text = null;
string strVal = hdnOption.Value;
IFormatProvider provider = new System.Globalization.CultureInfo("en-GB", true);
DateTime dtStart = new DateTime();
DateTime? dtEnd = null;
string strCity;
if (strVal == "today")
{
HideCustomSearch();
dtStart = DateTime.Today;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "weekly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddDays(-7).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "byweekly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddDays(-15).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "monthly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddMonths(-1).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "yearly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddYears(-1).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "custom")
{
ShowCustomSearch();
dtStart = DateTime.Now;
dtEnd = DateTime.Now;
strCity = txtCityName.Text.ToString().Trim();
strCity = null;
hdndtStart.Value = txtdtStart.ToString();
hdndtEnd.Value = txtdtEnd.Text.ToString();
}
FillGridFilter(dtStart, dtEnd, strCity);
P.S。它仅在最后一行“strCity”上给我错误
答案 0 :(得分:2)
您的错误发生是因为您在ifs之后的任何地方都没有“其他”。编译器无法验证是否将赋值'strCity'('strVal'可能有许多不同的选项)。 因此,您必须指定一个默认值。
将代码编写为switch语句: http://msdn.microsoft.com/en-us/library/vstudio/06tc147t.aspx 可能会更清楚,因为你可以在那些情况下定义一个'默认'案例。
答案 1 :(得分:0)
您必须为局部变量分配一些默认值。
在您的情况下会出现此错误,因为编译器认为string strCity;
可能永远不会被赋值。
声明string strCity;
为其指定一些值。
string strCity="";
或
string strCity=string.Empty;
试试这个,错误就会消失。
答案 2 :(得分:0)
因为你已经使用了具有很多条件的staments。该值将在运行时分配给 strCity 变量。但在if语句之后 strCity ,您已将 FillGridFilter 用作参数,因此编译器不会确定if条件是否为exicutes。那是方式
错误
使用未分配的局部变量'strCity' 它正在显示
最好将默认值分配给变量 strCity
答案 3 :(得分:0)
更好的是,将null
分配给strCity
,在条件逻辑中使用else if
代替if
,并在调用之前测试strCity
为空FillGridFilter
。
从我所看到的strVal变量的所有可能选项是互斥的,所以不需要在每次测试中强制重新评估它。
答案 4 :(得分:0)
最好放
string strCity=null;
或 string strCity = String.Empty;
但请确保FillGridFilter函数处理null或空值。
此致
Nitin Joshi