错误可空对象必须具有值 [英] Error nullable object must have a value

查看:90
本文介绍了错误可空对象必须具有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此错误指向我的组合框扩展类。我在使用pickListItem的3层应用程序中使用List集合。



我的comboboxExtension.cs

This error points to my combobox extension class. I use a List collection in a 3-layer app that uses a pickListItem.

My comboboxExtension.cs

public static int? SelectedPicklistNullableID(this ComboBox cb)
       {
           if (cb.SelectedItem == null) return null;
           return ((PickListItem)cb.SelectedItem).ID;
       }

       public static int SelectedPicklistID(this ComboBox cb)
       {
           return cb.SelectedPicklistNullableID().Value;
       }





在调试模式下,我可以看到下拉列表,然后选择一个值,这个发生错误。我是否需要添加列表<>到设计中组合框的Items属性?任何帮助表示赞赏。我不知道如何绑定到List。如果您需要更多代码,请告诉我。



In debug mode, I can see the dropdown list, then select a value, and this error occurs. Do I need to add a List<> to the Items property of the combobox in design? Any help is appreciated. I don't know how to bind to a List. If u need more code, let me know.

推荐答案

您只能使用可空类型的如果对象不为null。如果为null,则抛出异常。在尝试通过尝试获取值来解除引用之前,您可以先检查可空类型的对象是否为null。如果对象不为null,则可以获得 Value



可能是这样的:

You can use the Value of a nullable type only if the object is not null. If it is null, an exception is thrown. You can first check the object of a nullable type for null before trying to dereferencing it by an attempt to get the value. If the object is not null, you can get Value.

It could be something like this:
int? value = cb.SelectedPicklistNullableID();
if (value == null)
   return -1; // for example;
              // traditional index returned when nothing is selected
else
   return value.Value;



请注意-1 (更确切地说,索引小于零)选择协议,在选择的.NET控件中始终使用,使可空类型冗余。或者,您可以在任何地方使用可空类型,只有在您确实需要使用索引选择任何内容时才会使用 Value ,或者取消选择或确定是否选择了某些内容,但使用不可为空索引很简单,因为协议已经使用。



-SA


Note that "-1" (more exactly, index less then zero) selection agreement, which is always used in .NET controls with selection, makes nullable type redundant. Alternatively, you can use nullable type everywhere, taking Value only when you actually need to select anything using the index, or unselect or determine if something is selected, but using non-nullable indices is simple, because the agreement is already used.

—SA


这篇关于错误可空对象必须具有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆