asp.net - InvalidOperationException Nullable 对象必须有一个值

标签 asp.net c#-4.0

我正在使用 asp.net 4.0 和 sql server 当我在应用程序中浏览时,只有几次我看到这个错误,如果点击它解决的某些事情,有人可以建议我如何克服这个问题

'System.InvalidOperationException: Nullable 对象必须有一个值。
在 System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource
资源)

最佳答案

您可能正在尝试访问为空的可空对象的值。

来自 MSDN page on nullable types

The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.



您有多种选择来克服错误。例如:
int? a=null; // a test nullable object
//Console.WriteLine(a.Value); // this throws an InvalidOperationException

// using GetValueOrDefault()
Console.WriteLine(a.GetValueOrDefault()); //0 (default value for int)

//checking if a.HasValue
if(a.HasValue) Console.WriteLine(a.Value); // does not print anything as the if
                                           // is false

// using the ?? operator
Console.WriteLine(a ?? -1); // prints -1

关于asp.net - InvalidOperationException Nullable 对象必须有一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8902244/

相关文章:

linq - 使用 lambda 连接对象的字符串属性

javascript - VB.Net 中连续 4 个文本框的 gridview

c# - 实体 IEnumerable 仅获取基类 - 而不是派生类

java - 为什么通过 Android 向 ASP.NET MVC 站点发送 POST 数据时会出现错误 500?

c# - Assembly.GetExecutingAssembly() 和 typeof(program).Assembly 之间的区别

c# - 博客引擎2.0错误

c# - 使用当前线程区域性与两位数的月份和日期格式化日期?

asp.net - ASP.net WebForms 是 CPU 密集型平台吗?

c#-4.0 - ffmpeg 水印错误 : video pixel format unknown, Parser not found for codec

c# - 在 WCF 服务应用程序中找不到类型或命名空间名称 'var'