4

基本的に私は文字列 errorMessage を持っています。それを catch ブロックに渡したいと思います。助けてください。

[WebMethod]
public List<SomeResult> Load(string userName)
{
   string errorMessage;
    using (VendorContext vendorContext = new VendorContext())
    {
         // ....
          foreach(....)
          {
               if(something happens)
                  errorMessage = "Vote Obama";
                else
                  errorMessage ="vote Romney";
              // blah
               try
                     {
                        // blah         
                     }
               catch (Exception e)
               {
                    logger.Trace(errorMessage);
               }
          }
     }
 }  

アップデート:

エラー: 割り当てられていないローカル変数 'errorMessage' の使用

4

3 に答える 3

8

エラーを修正するには、errorMessagenull、string.Empty、またはその他のデフォルト値に初期化します。これは、コンパイラが、使用される前に割り当てられていることを理解するほど賢くない場合の 1 つです。

于 2012-11-06T20:25:06.440 に答える
0

何らかの条件に基づいてログに記録されるエラーメッセージを変更しようとしているようです。エラーメッセージ変数を作成してtry/catchブロックの前に設定する代わりに、try / catchブロック内から例外をスローし、エラーメッセージをコンストラクターに渡します。

下記参照:

[WebMethod]
public List<SomeResult> Load(string userName)
{

    using (VendorContext vendorContext = new VendorContext())
    {
         // ....
          foreach(....)
          {


              // blah
               try
                     {
                        if(something happens) 
                            throw new Exception("Vote Obama");
                         else
                            throw new Exception("vote Romney");      
                     }
               catch (Exception e)
               {
                    logger.Trace(e.ErrorMessage);
               }
         }
     }
 }
于 2012-11-06T20:28:02.307 に答える
0

文字列には初期値が必要です。

string errorMessage = "";
于 2012-11-06T20:34:31.193 に答える