获取集合属性

本文关键字:属性 集合 获取 | 更新日期: 2023-09-27 18:24:20

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

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

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);

如果我删除了那行,应用程序就不会崩溃了,我不知道我做错了什么,因为我没有收到任何错误。此外,如果这是一个糟糕的方法,请告诉我我想改进感谢

获取集合属性

创建无限递归的代码是:

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

您需要将"backing"字段与公共属性分开:

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

在上面的示例中,TheText是一个"名称不正确"的公共属性,text是后备字段。目前,您的代码正在为两者寻址同一字段,从而导致递归。通常,约定是具有大写属性Text和小写支持字段text

但是,在您的代码中,您已经将类命名为Text,因此寻址text.Text是令人困惑的。

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

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

要避免这种情况,请尝试此

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

或空获取设置方法

public class Text
{
    public  string text { get; set; }
}