fir*_*ast 5 c# stack-overflow overloading operator-keyword
几天前我开始用C#编程.
现在,当玩弄运算符重载时会出现一个令人困惑的错误.
以下代码在运行时生成StackOverflowException:
using System;
namespace OperatorOverloading
{
public class Operators
{
// Properties
public string text
{
get
{
return text;
}
set
{
if(value != null)
text = value;
else
text = "";
}
}
// Constructors
public Operators() : this("")
{
}
public Operators(string text)
{
// Use "set" property.
this.text = text;
}
// Methods
public override string ToString()
{
return text;
}
// Operator Overloading
public static string operator +(Operators lhs, Operators rhs)
{
// Uses properties of the passed arguments.
return lhs.text + rhs.text;
}
public static void Main(string[] args)
{
Operators o1 = new Operators();
Operators o2 = new Operators("a");
Operators o3 = new Operators("b");
Console.WriteLine("o1: " + o1);
Console.WriteLine("o2: " + o2);
Console.WriteLine("o3: " + o3);
Console.WriteLine();
Console.WriteLine("o1 + o2: " + (o1 + o2));
Console.WriteLine("o2 + o3: " + (o2 + o3));
}
}
}
Run Code Online (Sandbox Code Playgroud)
在阅读了Dirk Louis和Shinja Strasser的书"Microsoft Visual C#2008"中关于operater重载的章节后,我尝试编写了一个自己的例子.
也许有人知道出了什么问题.
谢谢.
Cᴏʀ*_*ᴏʀʏ 10
好吧,首先,运算符重载不会破坏您的代码.你得到一个,StackOverflowException因为你的text财产的吸气者正试图回归自己.
您应该为您的财产使用支持字段:
private string _text;
public string Text
{
get { return _text; }
set
{
if (value != null)
_text = value;
else
_text = string.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
.NET所做的是将您的属性转换为访问者和变异者 - 两种不同的方法.在您的原始示例中,您的代码将执行以下操作:
private string text;
public string get_text()
{
return get_text(); // <-- StackOverflowException
}
public void set_text(string value)
{
this.text = value;
}
Run Code Online (Sandbox Code Playgroud)
修正后的版本正确使用了支持字段:
private string text;
public string get_text()
{
return this.text; // Happy :)
}
public void set_text(string value)
{
this.text = value;
}
Run Code Online (Sandbox Code Playgroud)
您的类中的 get 代码块有问题,这就是导致 StackOverFlow 异常的原因。
public string text
{
get
{
return text;
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,当您说return text;它将去调用属性text本身的 get 块时,这会导致堆栈溢出。将您的属性文本包裹在私有 _txt 字符串字段中,它应该可以正常工作。
你可以把它做成这样的..
private string _txt;
public string text
{
get
{
return _txt;
}
set
{
_txt = string.IsNullOrEmpty(value) ? string.Empty : value;
}
}
Run Code Online (Sandbox Code Playgroud)