为什么属性集抛出异常计算器? [英] Why does Property Set throw StackOverflow exception?

查看:116
本文介绍了为什么属性集抛出异常计算器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java和通常会放在getter / setter方法​​。我感兴趣的是在C#中使用以下code这样做,但它抛出一个异常计算器。我在做什么错了?

调用code

  c.firstName =A;

属性code

 公共字符串的firstName;
{
    得到
    {
        返回的firstName;
    }
    组
    {
        的firstName =价值;
    }
}


解决方案

这是因为你在递归调用的属性 - 在设置你重新设置该属性,它继续的循环往复的,直到你吹堆栈。

您需要的私人支持字段保存的价值,例如

 私人字符串的firstName;公共字符串名字
{
    得到
    {
        返回this.firstName;
    }
    组
    {
        this.firstName =价值;
    }
}

另外,如果你正在使用C#3.0中,你可以使用自动属性,它会创建一个隐藏的后备字段,例如

 公共字符串名字{获得;组; }

I know java and would normally put in getter/setter methods. I am interested in doing it in C# with the following code, but it throws a StackOverflow exception. What am I doing wrong?

Calling Code

c.firstName = "a";

Property Code

public String firstName;
{
    get
    {
        return firstName;
    }
    set
    {
        firstName = value;
    }
}

解决方案

It's because you're recursively calling the property - in the set you are setting the property again, which continues ad infinitum until you blow the stack.

You need a private backing field to hold the value, e.g.

private string firstName;

public string FirstName
{
    get
    {
        return this.firstName;
    }
    set
    {
        this.firstName = value;
    }
}

Alternatively, if you're using C# 3.0, you could use an auto-property, which creates a hidden backing field for you, e.g.

public string FirstName { get; set; }

这篇关于为什么属性集抛出异常计算器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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