在switch语句中使用变量抛出和编译器错误

时间:2015-06-25 15:04:22

标签: c# switch-statement

尝试在交换机内部使用变量时遇到问题。它们是分配在"外部"的变量。 (开关)当我将它们作为参数传递时,它会抛出向下错误"使用未分配的变量""

    DateTime startDate, endDate;
                switch (int.Parse(cmbRepor.SelectedValue.ToString()))
                {
                    case 1:
                        startDate = new DateTime(anio, 1, 1);
                        endDate = new DateTime(anio, 3, 31);
                        break;
                    case 2:           
                        startDate = new DateTime(anio, 4, 1);
                        endDate = new DateTime(anio, 6, 30);
                        break;
                    case 3:
                        startDate = new DateTime(anio, 7, 1);
                        endDate = new DateTime(anio, 9, 30);
                        break;
                    case 4:
                        startDate = new DateTime(anio, 10, 1);
                        endDate = new DateTime(anio, 12, 31);
                        break;
                    default:
                        break;
                }

        ReporteLogica logica = new ReporteLogica();

            switch (int.Parse(cmbRepor.SelectedValue.ToString()))
            {
                case 1:
                    dgvListado.DataSource = logica.GetReporteClientesCuentasInhabilitadas(startDate, endDate);
                    break;
                case 2:
                    dgvListado.DataSource = logica.GetReporteClientesCuentasInhabilitadas(startDate, endDate);
                    break;
                case 3:
                    dgvListado.DataSource = logica.GetReporteClientesCuentasInhabilitadas(startDate, endDate);
                    break;
                case 4:
                    dgvListado.DataSource = logica.GetReporteClientesCuentasInhabilitadas(startDate, endDate);
                    break;
                default:
                    break;
            }

1 个答案:

答案 0 :(得分:1)

问题是您没有在交换机的默认情况下分配值。那么,如果没有条件适合,那么价值应该是多少呢?它保持未初始化,由于您在运行时在程序中所做的任何限制,编译器不知道这是否可能。为您的日期分配一个defualt值:

DateTime startDate = DateTime.Now, endDate = DateTime.Now;