Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

c# - Getting StackOverflowException when setting property

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;
    }

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

Class definition is here.

[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?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...