C# - 在不知道变量的情况下初始化变量

Jor*_*man 5 .net c# asp.net scope variable-initialization

我的数据库中有两个不同的表,每个表都根据其"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)
        {
        }
    }
Run Code Online (Sandbox Code Playgroud)

显而易见的问题是我需要在if语句之前启动currentValue变量,否则它的"可能性"永远不会被声明,因此函数的其余部分(利用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);
    }
Run Code Online (Sandbox Code Playgroud)

[编辑]更改了标题,使其更准确地反映了我的问题

age*_*t-j 8

在C#中,所有类型都需要一个类型.如果您的Table#类型扩展DataModel.DataAccess.Table,请使用:

DataModel.DataAccess.Table currentValue;
Run Code Online (Sandbox Code Playgroud)

否则,你需要找到一个共同的基类(对象是他们所有人的曾祖父).

object currentValue;
Run Code Online (Sandbox Code Playgroud)

由于您没有初始化currentValue,编译器无法知道您的意思是什么类型var.这就是你得到例外的原因.

附录:也许,您可以使用通用方法,而不是传递表的名称,如下所示:

moveUp(dc.Table1, item => item.Table1Key, "george");

void moveUp<T> (IEnumerable<T> table, Func<T,string> keySelector, string ValId)
{
    T currentValue = table.Single(item => keySelector(item) == ValueId);

    try
    {
        //make the change and update the database and gridview
    }
    catch (InvalidOperationException)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)