[英]integer fields set as null
How to make an integer field accepts null values?如何使整数字段接受空值?
[Range(10, 65]
[Display(Name = "oh")]
public int oh { get; set; }
I'm currently using this code, but I'm getting not null
on sql server (I haven't used [Required]).我目前正在使用此代码,但我在 sql server 上
not null
(我没有使用 [Required])。
Thanks a lot!非常感谢!
Use ?
使用
?
keyword关键词
public int? oh { get; set; }
It makes the type a Nullable
type.它使类型成为
Nullable
类型。 Now you can set null
to oh
现在您可以将
null
设置为oh
And then check for its value by:然后通过以下方式检查其值:
if(oh.HasValue){
Console.WriteLine(oh.Value)
}
.HasValue
says if it has value or null. .HasValue
表示它是否有值或为空。
.Value
gets you the actual value .Value
您提供实际价值
use用
int?内部? for the data type.
为数据类型。
I don't know how this will work in conjunction with Range...我不知道这将如何与 Range 结合使用...
You can use a nullable type:您可以使用可为空类型:
int? intNullable = null;
With a nullable type, you have another features like a bool property called HasValue
which return if the int has a value and Value
to get a value without nullable.使用可空类型,您还有另一个功能,例如名为
HasValue
的 bool 属性,如果 int 具有值则返回,而Value
则可获取不可以为空的值。
if (intNullable.HasValue)
{
int value = intNullable.Value;
}
In your case在你的情况下
public int? oh { get; set; }
The difference it the int
is a value type
while int?
int
是value type
而int?
的区别是int?
is a reference type.是引用类型。 The
?
?
is just a shortcut to Nullable<T>
class.只是
Nullable<T>
类的快捷方式。 Value types cannot be null, reference type can.值类型不能为空,引用类型可以。 Read more about here http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
阅读更多关于这里http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
You can use ?您可以使用 ? in cases where a value type might be null:
在值类型可能为 null 的情况下:
public int? oh { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.