Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-检查是否设置了integer属性_C#_Properties - Fatal编程技术网

C#-检查是否设置了integer属性

C#-检查是否设置了integer属性,c#,properties,C#,Properties,我正在验证一些属性,我需要知道其他层是否设置了long或integer值 例如,此类:: public class Person { public int Age {get;set;} } 当我设置Person的新实例时,Age的值为0。但是我必须验证是否设置了年龄,因为年龄可以为零(当然不是在这个上下文中) 我想到的一个解决方案是将int用作可为空的整数(public int?Age),并在Person的构造函数中将Age设置为空 但是我试图避免它,因为我不得不改变太多的类,只是为

我正在验证一些属性,我需要知道其他层是否设置了long或integer值

例如,此类::

public class Person 
{
    public int Age {get;set;}
}
当我设置Person的新实例时,Age的值为0。但是我必须验证是否设置了年龄,因为年龄可以为零(当然不是在这个上下文中)

我想到的一个解决方案是将int用作可为空的整数(public int?Age),并在Person的构造函数中将Age设置为空

但是我试图避免它,因为我不得不改变太多的类,只是为了检查Age.HasValue,并将其用作Age.Value


任何建议?

Int的默认值初始化为0;假设您不想使用
int?
,这将非常适合您。您可以对此进行检查,也可以使用标志和支持字段:

private int _age;
public int Age 
{ 
  get { return _age; } 
  set { _age = value; _hasAge = true; } 
}

public bool HasAge { get { return _hasAge; } }
如上所述,您可以将其初始化为无效状态:

private int _age = -1;
public int Age 
{ 
  get { return _age; } 
  set { _age = value; _hasAge = true; } 
}

public bool HasAge { get { return _age != -1; } }
或者只需分解并使用
int?

public int? Age { get; set; }
public bool HasAge { get { return Age.HasValue; } }
为了向后兼容您的代码,您可以将其从
int?
中退出来,而不公开它:

private int? _age;
public int Age
{
  get { return _age.GetValueOrDefault(-1); }
  set { _age = value; }
}

public bool HasAge { get { return _age.HasValue; } }
已显式设置为默认值的字段(或自动实现的属性)与从未设置的字段(或属性)之间没有区别

A<代码>可空绝对是这里的方法,但您需要考虑使用最干净的API。

例如,您可能需要:

public class Person 
{
    private int? age;

    public int Age
    {
        // Will throw if age hasn't been set
        get { return age.Value; }
        // Implicit conversion from int to int?
        set { age = value; }
    }

    public bool HasAge { get { return age.HasValue; } }
}

这将允许您在假定已设置的位置直接读取
Age
,但在他们需要小心时进行测试。

无论您使用何种模式,您都必须先进行“已设置”查询,然后才能获得值,因此

使用可为空的字段
int?获取/设置属性使用的年龄,并查询
IsAgeSet
属性:

public class Person  
{ 
    private int? age;

    public int Age {
        get {return age.Value;} // will fail if called and age is null, but that's your problem......
        set {age = value;}
    }
    public bool IsAgeSet {
        get {return age.HasValue;}
    }
}

您必须更改许多类这一事实是一个薄弱的论点,因为任何可能的解决方案都会涉及大量的更改。听起来您希望您的值类型有一个额外的“nullable”状态。当然,这正是
int?
的用途。