如何在c#中将Int 0设置为null [英] How to set Int 0 to null in c#

查看:844
本文介绍了如何在c#中将Int 0设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,



请建议一些方法或示例,将Int = 0设置为null,如果Int字段为null或相应为零,则将日期设置为null在C#。

Dear All,

Please suggest some methods or example, to set Int = 0 to null and set the date also null if Int field is null or zero correspondingly in C#.

推荐答案

除非通过在声明中添加?后缀将它们特别声明为可空类型,否则整数不能为空:
Integers cannot be null unless you declare them specifically as a "nullable type" by adding the '?' Suffix to the declaration:
int? myNullableInt = null;


它们是在c#.Net中将int声明为Nullable的两种方法。



第一个是

Nullable< int> i = null;



和第二个是

int? d = null;
Their are two ways to declare int as Nullable in c# .Net.

First one is
Nullable<int> i = null;

and the Second is
int? d = null;


你也可以这样做:

You could also do something like:
public class NullableIntExample
{
  private int i = 0;
  private DateTime dt = DateTime.Now;

  public int? I 
  {
    get
    { 
      if (this.i == 0)
      {   
        return null;
      }
      else
      {
         return this.i; 
      }
   }

  public DateTime? DT 
  {
    get
    { 
      if (this.i == 0)
      {   
        return null;
      }
      else
      {
         return this.dt; 
      }
   }

}


这篇关于如何在c#中将Int 0设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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