如何在c#中将Int 0设置为null

如何在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; 
      }
   }

}