我在数据库中有两个不同的表格,每个表格都基于它们的“SortOrder”向用户显示。我编写了两个函数,它们接受一行(或实体)并将其排序顺序与最近的一个交换(向上或向下,取决于执行哪个函数)。根据事件发生的位置(具有相同功能的多个网格视图),我需要使这些函数适用于两个不同的表格。以下是我目前的代码(再次说明,移动向下的几乎相同的函数,但我不会发布它,因为这将是冗余的):
protected void moveUp(String ValId, String dbName)
{
int ValueId = Convert.ToInt32(ValId);
DataModel.DataAccess.Entities dc = new DataModel.DataAccess.Entities();
if (dbName.ToLower() == "table1")
{
DataModel.DataAccess.Table1 currentValue = dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
}
else if (dbName.ToLower() == "table2")
{
DataModel.DataAccess.Table2 currentValue = dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
}
try
{
//make the change and update the database and gridview
}
catch (InvalidOperationException)
{
}
}
明显的问题是,在if语句之前需要初始化"currentValue"变量,否则有可能永远不会被声明,因此使用当前值变量的函数的其余部分将无法工作。
我的问题是:如果我不确定它将是什么,应该如何在if语句之前初始化变量?我认为这可能会起作用,但它说我仍然需要初始化它("隐式类型本地变量必须初始化")。
var currentValue; //this is the line where I get the error message above
if (dbName.ToLower() == "table1")
{
currentValue = (DataModel.DataAccess.Table1)dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
}
else if (dbName.ToLower() == "table2")
{
currentValue = (DataModel.DataAccess.Table2)dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
}
[编辑] 更改标题以更准确地反映我的问题