0

所以我试图在 C# 上使用 get/set 属性,但我无法让我的代码工作(它使我的控制台应用程序崩溃)

这是我的 textHandler.cs 文件,您可以看到公共静态 void 方法 WriteInfo 正在使用 get/set 属性,但它使我的应用程序崩溃。

class TextHandler
{
    public static void WriteInfo(String text)
    {
        var consoleText = new Text();
        consoleText.text = text;
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine(consoleText);
        Console.ForegroundColor = ConsoleColor.White;
    }
    public static void WriteError(String text)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(text);
        Console.ForegroundColor = ConsoleColor.White;
    }
    public static void WriteSuccess(String text)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(text);
        Console.ForegroundColor = ConsoleColor.White;
    }
    public static void WriteText(String text, ConsoleColor color)
    {
    }
}
public class Text
{
    public String text
    {
        get
        {
            return this.text;
        }
        set
        {
            this.text = value;
        }
    }
}

这里我称之为方法

TextHandler.WriteInfo("New client with version : " + message + " | current version : " + version);

如果我删除该行应用程序不再崩溃,不知道我做错了什么,因为我没有收到任何错误。另外,如果这是一种不好的方法,请告诉我我想改进谢谢

4

4 回答 4

6

创建无限递归的代码是:

public String text
    {
        get
        {
            return this.text;
        }
        set
        {
            this.text = value;
        }
    }

在集合中,你分配this.text = value给自己,创建无限递归,迟早StackOverflow

似乎您不需要字段,因此将代码更改为:

 public String Text {get;set} //PROPERTIES ARE UPPERCASE BY MS STANDART
于 2013-07-23T13:07:55.587 回答
4

您需要将“支持”字段与公共属性分开:

public class Text
{
    private string text;

    public String TheText
    {
        get
        {
            return this.text;
        }
        set
        {
            this.text = value;
        }
    }
}

在上面的示例中,TheText是一个“命名错误”的公共属性,并且text是支持字段。目前,您的代码正在为两者寻址相同的字段,从而导致递归。通常约定是有一个大写属性Text和一个小写的支持字段text

但是,在您的代码中,您已经命名了该类Text,因此对 address 感到困惑text.Text

于 2013-07-23T13:08:23.963 回答
1

无需创建“文本”类。只需将字符串传递给 Console.WriteLine。此外,您没有指定应用程序的性质。这在控制台应用程序中可以正常工作,但可能不适用于未绑定到 SdtOut 的 Web 应用程序或其他应用程序

于 2013-07-23T13:08:04.237 回答
1

因此,您将设置到再次调用 set 方法的属性中,直到您获得 StackOverflow 异常。

为了避免这种情况,试试这个

public class Text
{
    string _text = null;
    public String text
    {
        get
        {
            return this.text;
        }
        set
        {
            _text = value;
        }
    }
}

或者清空get set方法

public class Text
{
    public  string text { get; set; }
}
于 2013-07-23T13:14:35.600 回答