设置属性时获取StackOverflowException [英] Getting StackOverflowException when setting property

查看:74
本文介绍了设置属性时获取StackOverflowException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public List<Empleado> ListarEmpleados()
    {
        List<Empleado> returnList = new List<Empleado>();
        var lista = from u in DB.tabEmpleado
                    select new
                    {
                        u.idEmpleado,
                        u.idUsuario,
                        u.Nombre,
                        u.Apellidos,
                        u.Telefono1
                    };                           
        foreach (var e in lista)
        {
            Empleado empleado = new Empleado();
            empleado.idEmpleado = e.idEmpleado;
            empleado.idUsuario = e.idUsuario;
            empleado.nombre = e.Nombre;
            empleado.apellidos = e.Apellidos;
            empleado.telefono1 = e.Telefono1;
            returnList.Add(empleado);                
        }
        return returnList;
    }

这是一个WCF服务,在被调用时它将在类定义中恰好在idEmpleado的Set属性中返回StackOverflow错误.

This is a WCF service, when is called it returns StackOverflow error in the class definition, exactly in the Set property of idEmpleado.

类定义在这里.

[DataContract]
public class Empleado
{                
    private int _idEmpleado;
    [DataMember(IsRequired = false)]
    public int idEmpleado
    {
        get { return _idEmpleado; }
        set { idEmpleado = value; } ERROR
    }


    private int _idUsuario;
    [DataMember(IsRequired = false)]
    public int idUsuario
    {
        get { return _idUsuario; }
        set { idUsuario = value; }
    }

    private string _nombre;
    [DataMember(IsRequired = false)]
    public string nombre
    {
        get { return _nombre; }
        set { nombre = value; }
    }

    private string _apellidos;
    [DataMember(IsRequired = false)]
    public string apellidos
    {
        get { return _apellidos; }
        set { apellidos = value; }
    }

    private string _telefono1;
    [DataMember(IsRequired = false)]
    public string telefono1
    {
        get { return _telefono1; }
        set { telefono1 = value; }
    }
}

}

有人知道错误在哪里吗?

Does anybody know where the error is?

谢谢.

推荐答案

您正在通过再次调用属性设置器来设置属性的值,而不是直接设置其后备字段.这将导致无限递归并导致堆栈溢出.

You are setting the value of the property by calling the property setter again, instead of directly setting its backing field. This causes an infinite recursion and a stack overflow as a result.

public int idEmpleado
{
    get { return _idEmpleado; }
    set { idEmpleado = value; } // SHOULD BE _idEmpleado = value
}

这篇关于设置属性时获取StackOverflowException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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