C#从单选按钮设置bool属性

时间:2011-12-14 15:05:38

标签: c# properties boolean stack-overflow

我的单选按钮有问题。我正在做的是创建一个客户对象,同时我想在客户基类中设置每个单选按钮的一个bool属性。我得到的错误消息是“StackOverflowException Unhandeled”。错误指向此“IsClient = value;”在CustomerType类中。

这是我创建Customer对象的位置(在CustomerForm.cs中)

m_customer = new Customer(radioClient.Checked, radioProspect.Checked, radioCompany.Checked, radioPrivate.Checked);


public class Customer : CustomerType
{
private Contact m_contact;
private string m_id;

public Customer()
{
    m_id = string.Empty;
}

public Customer(bool client, bool prospect, bool company, bool priv)
{
    base.IsClient = client;
    base.IsProspect = prospect;
    base.IsCompany = company;
    base.IsPrivate = priv;
    m_id = string.Empty;
}

public Customer(Contact contactData)
{ m_contact = contactData; }

public Customer(string id, Contact contact)
{
    m_id = id;
    m_contact = contact;
}

public Contact ContactData
{
    get { return m_contact; }
    set {
        if (value != null)
            m_contact = value;  
    }
}

public string Id
{
    get { return m_id; }
    set { m_id = value; }
}

public override string ToString()
{
    return m_contact.ToString();
}
}


public class CustomerType 
{

public bool IsClient
{
    get { return IsClient; }
    set { IsClient = value; }
}

public bool IsCompany
{
    get { return IsCompany; }
    set { IsCompany = value; }
}

public bool IsPrivate
{
    get { return IsPrivate; }
    set { IsPrivate = value; }
}

public bool IsProspect
{
    get { return IsProspect; }
    set { IsProspect = value; }
}

}

2 个答案:

答案 0 :(得分:3)

CustomerType中的所有属性都是递归的 - 它们会炸掉堆栈。

看看这个:

public bool IsClient
{
    get { return IsClient; }
    set { IsClient = value; }
}

当您尝试获取IsClient属性的值时,则尝试获取IsClient属性的值。然后尝试获取IsClient属性的值...

将这些实现为自动实现的属性:

public bool IsClient
{
    get; set;
}

或者有一个合适的支持领域:

private bool isClient;
public bool IsClient
{
    get { return isClient; }
    set { isClient = value; }
}

答案 1 :(得分:1)

属性是一种功能。你写的相当于写作:

public void DoSomething()
{
    DoSomething();  // infinite recursion
}

错误代码:

public bool IsClient
{
    get { return IsClient; }
    set { IsClient = value; }
}

正确的代码:

public bool IsClient
{
    get { return _isClient; }
    set { _isClient = value; }
}
private bool _isClient;

或者在C#3.0或更高版本中,您可以将自动实现的属性用于简单的属性:

public bool IsClient { get; set; }
相关问题