2012-09-03 28 views
2

我對C#還很陌生,希望對我的代碼有所幫助。聲明空字節 - 可爲空的對象必須有一個值?

我正在創建一個用戶配置文件頁面,並在「photo =(byte)user.Photo;」上獲取錯誤「Nullable object must have a value」在下面的代碼中。我認爲這是因爲我宣佈「photo = 0;」我如何給它添加一個值?

更新:

這裏就是整個方法

 public static bool UserProfile(string username, out string userID, out string email, out byte photo) 
    { 

     using (MyDBContainer db = new MyDBContainer()) 
     { 

      userID = ""; 
      photo = 0; 
      email = ""; 
      User user = (from u in db.Users 
         where u.UserID.Equals(username) 
         select u).FirstOrDefault(); 
      if (user != null) 
      { 
       photo = (byte)user.Photo; 
       email = user.Email; 
       userID = user.UserID; 
       return true; // success! 
      } 
      else 
      { 
       return false; 
      } 
     } 
    } 
+0

什麼是用戶類型。照片','可空'或'字節?'? –

+1

你在哪裏宣佈'照片'?編譯時或執行時錯誤嗎? 'user.Photo'的類型是什麼?你可以創建一個簡短的但完整的程序來展示問題嗎? –

+1

'user.Photo'的計算結果爲'null'(這是什麼導致這種異常消息,當'Value'被調用時可爲空)。試試:'user.Photo ?? 0',但是要理解其含義..或者將'photo'聲明爲同一類型。 – 2012-09-03 17:06:44

回答

0

我假設你正在爲這一個得到錯誤...

if (user != null) 
     { 
      photo = (byte)user.Photo; 
      email = user.Email; 
      userID = user.UserID; 
      return true; // success! 
     } 
     else 
     { 
      return false; 
     } 

如果是的話那麼就用替換它。 ..

if (user != null) 
     { 
      photo = user.Photo== null ? null : (byte)user.Photo; 
      email = user.Email; 
      userID = user.UserID; 
      return true; // success! 
     } 
     else 
     { 
      return false; 
     } 
相關問題