2013-08-01 76 views
0

當我運行這段代碼我就趕上(例外五)部分得到了一個錯誤,我不知道爲什麼,編譯器說的「當地命名爲「E」變量不能在此範圍中聲明,因爲它會給予不同的意義,「E」,這已經是一個「父母或電流」範圍用來表示別的東西」我上「例外」部分的錯誤,我不知道爲什麼

 try 
     { 

      //Form Query which will insert Company and will output generated id 
      myCommand.CommandText = "Insert into Comp(company_name) Output Inserted.ID VALUES (@company_name)"; 
      myCommand.Parameters.AddWithValue("@company_name", txtCompName); 
      int companyId = Convert.ToInt32(myCommand.ExecuteScalar()); 

      //For the next scenario, in case you need to execute another command do it before committing the transaction 

      myTrans.Commit(); 

      //Output Message in message box 
      MessageBox.Show("Added", "Company Added with id" + companyId, MessageBoxButtons.OK, MessageBoxIcon.Information); 

     } 

     catch (Exception e) 
     { 
      try 
      { 
       myTrans.Rollback(); 
      } 
      catch (SqlException ex) 
      { 
       if (myTrans.Connection != null) 
       { 
        MessageBox.Show("An exception of type " + ex.GetType() + 
             " was encountered while attempting to roll back the transaction."); 
       } 
      } 

      MessageBox.Show("An exception of type " + e.GetType() + 
           "was encountered while inserting the data."); 
      MessageBox.Show("Record was written to database."); 

     } 
     finally 
     { 
      myConnection.Close(); 
     } 

希望你的回覆!謝謝!

+1

請注意,如果您在MSDN中查找錯誤代碼(如CS0136在你的情況下),你會得到的文章,解釋常見的情況,並展示樣品 - [編譯器錯誤CS0136(http://msdn.microsoft.com/en-us /library/973aa6bt%28v=vs.90%29.aspx) –

回答

4

你有一個變量在局部範圍內命名e別的地方就沒有辦法兩者之間的歧義。

很可能你在一個事件處理函數中,EventArgs參數名爲e,你應該重命名其中一個e標識符。

下面的例子演示此問題:

  1. 有衝突的參數名稱

    void MyEventHandler(object source, EventArgs e) 
    //           ^^^ 
    { 
        try 
        { 
         DoSomething(); 
        } 
        catch (Exception e) 
        //    ^^^ 
        { 
         OhNo(e); 
         // Which "e" is this? Is it the Exception or the EventArgs?? 
        } 
    } 
    
  2. 相沖突的局部變量

    void MyMethod() 
    { 
        decimal e = 2.71828; 
        //  ^^^ 
    
        try 
        { 
         DoSomething(); 
        } 
        catch (Exception e) 
        //    ^^^ 
        { 
         OhNo(e); 
         // Which "e" is this? Is it the Exception or the Decimal?? 
        } 
    } 
    
  3. 匿名函數(拉姆達)

    void MyMethod() 
    { 
        decimal e = 2.71828; 
        //  ^^^ 
    
        var sum = Enumerable.Range(1, 10) 
             .Sum(e => e * e); //Which "e" to multiply? 
        //      ^^^ 
    } 
    

請注意以下事項不會導致同樣的錯誤,因爲你可以與this關鍵字歧義:

class MyClass 
{ 
    int e; 

    void MyMethod() 
    { 
     try 
     { 
      DoSomething(e); //Here it is the Int32 field 
     } 
     catch (Exception e) 
     { 
      OhNo(e); //Here it is the exception 
      DoSomethingElse(this.e); //Here it is the Int32 field 
     } 
    } 

} 
0

這意味着越早宣佈A E變量命名,現在在相同的代碼塊或其內部的塊(此try/catch塊)中,您再次聲明它。將異常e更改爲Exception except,它可能會起作用。

相關問題