gpt4 book ai didi

c# - 声明空字节 - 可空对象必须有一个值?

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:59 25 4
gpt4 key购买 nike

我对 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;
}
}
}

最佳答案

我假设你在这方面遇到了错误......

  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;
}

关于c# - 声明空字节 - 可空对象必须有一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12251711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com