2013-08-01 75 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,它可能会起作用。

相关问题