为什么 Property Set 会抛出 StackOverflow 异常? [英] Why does Property Set throw StackOverflow exception?

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

问题描述

我知道 java 并且通常会使用 getter/setter 方法.我有兴趣使用以下代码在 C# 中执行此操作,但它会引发 StackOverflow 异常.我做错了什么?

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?

调用代码

c.firstName = "a";

属性代码

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

推荐答案

这是因为您正在递归调用该属性 - 在 set 中您再次设置该属性,继续ad无限,直到你把堆栈炸毁.

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

或者,如果您使用的是 C# 3.0,您可以使用自动属性,它会为您创建一个隐藏的支持字段,例如

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

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

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