超载get​​ter和setter原因计算器在C#计算器、原因、get、ter

由网友(╉偝靠偝╊)分享简介:我不知道是什么原因造成的StackOverflowException当我尝试覆盖get和set功能。当我只使用默认get和set它的工作原理。I am not sure what is causing the StackOverflowException when I try to overwrite a get a...

我不知道是什么原因造成的StackOverflowException当我尝试覆盖get和set功能。当我只使用默认get和set它的工作原理。

I am not sure what is causing the StackOverflowException when I try to overwrite a get and set function. When I just use the default get and set it works.

enum MyEnumType
{
....
}

public MyEnumType data { get; set; }

但是,当我尝试添加更多的数据时,它抛出一个StackOverflowException

But when I try to add additional data, it throws a StackOverflowException

public MyEnumType data 
{
  get
  {
    return data;
  }
  set 
  {
    data = value;
  }
}

任何想法?当我做到这一点的ASP.NET的用户控件的属性是没有问题的。我很奇怪,为什么它是造成StackOverflowException一个正常的枚举数据类型。

Any ideas? When I do this for asp .net user control attributes there is no problem. I am wondering why it is causing a StackOverflowException for a normal enum data type.

推荐答案

是的,你没有一个支持字段...这是你应该怎么做:

Yes, you do not have a backing field... this is how you should do it:

 private MyEnumType data;

public MyEnumType Data 
{
  get
  {
    return data;
  }
  set 
  {
    data = value;
  }
}

会发生什么事是你指的是属性返回自身,这将导致试图访问其自身的价值无限循环。因此,计算器。

What happens is that you are referring to the property to return itself, this causes an infinite loop of trying to access its own value. Hence, StackOverFlow.

在你的情况下,当你不添加任何额外的逻辑在get和set方法,你可以使用自动属性也是如此。这是简单的定义如下:

In your case when you do not add any additional logic in the get and set methods you could use an automatic property as well. This is simply defined like so:

public MyEnumType Data 
{
  get;
  set;
}
阅读全文

相关推荐

最新文章