C #-무엇이 될지 모른 채 변수 초기화

로 바꾸는 두 개의 함수를 작성했습니다. 데이터베이스에 두 개의 다른 테이블이 있으며 각 테이블은 "SortOrder"를 기반으로 사용자에게 표시됩니다. 행 (또는 엔터티)을 가져와 정렬 순서를 가장 가까운 순서 (실행중인 함수에 따라 위 또는 아래)로 바꾸는 두 개의 함수를 작성했습니다. 이벤트가 발생하는 위치 (동일한 기능을 가진 여러 gridview)에 따라 두 개의 다른 테이블에 대해 이러한 함수가 작동하도록해야합니다. 지금까지 제가 가지고있는 것은 다음과 같습니다 (다시 말하지만 아래로 이동하는 것과 거의 동일한 기능이 있지만 중복되기 때문에 게시하지 않겠습니다).

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 변수 를 시작하려면, 그렇지 않으면 선언되지 않은 "가능성"이 있으므로 나머지 함수 (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);
    }

[편집] 내 질문을 더 정확하게 반영하도록 제목 변경

5
задан Jordan Foreman 28 June 2011 в 18:06
поделиться