You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C#的Get和Set属性正常工作?Set内If语句引发错误

解决StackOverflowException异常问题

你的代码抛出System.StackOverflowException是因为Book类的Author属性在get和set方法里错误地引用了自身,而非对应的私有字段,导致无限递归调用:

  • 在getter方法中,return Author;会不断触发getter的调用,陷入死循环
  • 在setter方法中,无论分支是Author = value;还是Author = "Unknown";,都会不断触发setter的调用,同样陷入死循环

修正后的Book类代码

namespace Testing
{
    internal class Book
    {
        private string author;

        public Book(string inputAuthor)
        {
            Author = inputAuthor;
        }

        public string Author
        {
            get
            {
                // 返回私有字段author,而非属性自身
                return author;
            }
            set
            {
                if (value == "Adam Omar"  || value == "Adam")
                {
                    // 给私有字段author赋值,而非属性自身
                    author = value;
                }
                else
                {
                    author = "Unknown";
                }
            }
        }
    }
}

修正说明

  • getter方法改为返回私有字段author,终止递归调用
  • setter方法改为给私有字段author赋值,不再触发setter的重复调用

修正后运行程序:

  • 输入"Adam"或"Adam Omar"时,Author属性会正确返回对应名称
  • 输入其他内容时,Author属性会返回"Unknown"
  • 不会再出现栈溢出异常和无限输出的情况

内容的提问来源于stack exchange,提问作者Adam Omar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:00:58