C# getter 和 setter 在添加验证时返回 null



我正在我的代码上实现 getter 和 setter,但我的 getter 和 setter 遇到了问题,在 setter 中使用代码进行验证时,它总是返回 null,这是我的代码:

private string _employeeId;
public string EmployeeId
{
    get
    {
        return this._employeeId
    }
    set
    {
        if (!String.IsNullOrEmpty(this._employeeId))
        {
            this._employeeId = value;
        }
        else 
        {
            throw new Exception("Employee ID is required");
        }
    }  
}

在我的应用程序中,我分配了 _employeeId 的值创建类的对象

 Employees obj = new Employees();
 obj.EmployeeId = txt_empId.Text;

setter 正在尝试设置局部变量,但永远不会设置它,因为IsNullOrEmpty(this._employeeId)返回 true ,阻止它被设置。也许你的意思是检查value IsNullOrEmpty??

在代码中,变量_employeeId为空,因为您没有为其设置初始值。 在 set 方法中,您是验证变量_employeeId,因此此结果始终为 null,然后抛出异常! 我想你想验证一个值什么是设置方法输入值。所以你必须验证变量value,而不是变量_employeeId

private string _employeeId;
public string EmployeeId
{
    get
    {
        return this._employeeId
    }
    set
    {
        if (!String.IsNullOrEmpty(value))
        {
            this._employeeId = value;
        }
        else 
        {
            throw new Exception("Employee ID is required");
        }
    }  
}

最新更新