StackoverFlowException在C# [英] StackoverFlowException in C#

查看:78
本文介绍了StackoverFlowException在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个代码,在C#中设置属性,并得到一个例外。

 公共类人
{
公共字符串名称
{

{
的name = value;
}
得到
{
返回名称;
}
}

公共静态无效的主要()
{

人P =新的人();
p.name =比拉尔;

Console.WriteLine(p.name);
}
}


解决方案

您有无穷的递归你的财产 - 你的setter方法​​调用自身,直到你得到一个堆栈溢出:

 设置
{
产品名称=值;
}



相反,无论使用的自动财产(建议,如果你不需要支持字段的直接访问,并没有做你的getter任何其他操作/ setter方法​​):

 公共字符串名称{;设置;} 

或者使用支持字段:

 私人字符串_name; 
公共字符串名称
{

{
_name =价值;
}
得到
{
返回_name;
}
}


I am writing a code for setting the property in C# and getting an exception.

public class person
{
    public string name
    {
        set
        {
            name = value;
        }
        get
        {
            return name;
        }
    }

    public static void Main()
    {

        person p = new person();
        p.name = "Bilal";

        Console.WriteLine(p.name);
    }
}

解决方案

You have infinite recursion in your property - your setter will call itself until you get a stack overflow:

    set
    {
        name = value;
    }

Instead either use an auto-property (recommended if you don't need direct access to the backing field and are not doing any other operation in your getter/setters):

public string name {get;set;}

Or use a backing field:

private string _name;
public string name
{
    set
    {
        _name = value;
    }
    get
    {
        return _name;
    }
}

这篇关于StackoverFlowException在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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