在C#集合堆栈溢出错误/获取 [英] Stack overflow error in C# set/get

查看:140
本文介绍了在C#集合堆栈溢出错误/获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是工作在上周五的应用程序的公众意见一部分,当我得到一个堆栈溢出错误,这迷惑了我,所以我想我会寻求帮助。和搜索使用表达式堆栈溢出的网页是有点弄巧成拙!

I was working on a public comments part of an application on Friday when I got a stack overflow error, which confused me so I thought I'd ask for help. And searching the web using the expression 'stack overflow' is a bit self-defeating!

我希望做一个的HTMLEncode场上的SET语句中的类,之前发送的类的实例被添加到数据库:

I wanted to do an HtmlEncode on the set statement of the field in the class, before sending an instance of the class to be added to the database:

public class Feedback
{

    public Feedback() { }

    public string FeedbackComment
    {
        get { return FeedbackComment; }
        set {System.Web.HttpUtility.HtmlEncode(value); }
    }

    // other fields 

    // methods
}

这是造成计算器的错误,我已经通过更改代码修复的错误是这样的:

This was causing StackOverflow errors, I've fixed the error by changing the code to look like this:

public class Feedback
{

    public Feedback() { }

    private string feedbackComment;

    public string FeedbackComment
    {
        get { return feedbackComment; }
        set { feedbackComment = System.Web.HttpUtility.HtmlEncode(value); }
    }

    // other fields 

    // methods
} 

但我只是想为什么第一个GET / SET语句是如此递归他们造成堆栈溢出的解释,但恢复的代码时,看起来更像是C#2.0的工作? ?!请尽量温柔

But I just wanted an explanation of why the first get/set statements were so recursive that they caused a stack overflow but when reverting the code to look more like c#2.0 worked? Can this be achieved with the shorter syntax and if so how?

这是我的第一个问题上,所以要实现

This is my first question on SO - please try to be gentle!

推荐答案

第一实施例的吸气剂返回属性本身,而不是一个后备字段。

The getter of the first example is returning the property itself, not a backing field.

// The property name is "FeedbackComment"
public string FeedbackComment
{
    // And here you are returning "FeedbackComment" which is
    // creating the stack overflow
    get { return FeedbackComment; }
}



不幸的是没有办法缩短你有什么,可自动实现的属性(即公共字符串FeedbackComment {获取;设置;} )必须空getter和setter块是语法正确。没有什么不对您的第二个例子 - 是的,这是一个有点冗长,但很显然,简洁,能够完成任务。

Unfortunately there is no way to shorten what you have, automatically implemented properties (i.e. public String FeedbackComment { get; set; }) must have empty getter and setter blocks to be syntactically correct. There is nothing wrong with your second example - yes, it is a bit verbose but it is clear, concise, and gets the job done.

这篇关于在C#集合堆栈溢出错误/获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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