C# 获取集属性
因此,我试图在C#上使用get/set属性,但我的代码无法正常工作(这会使我的控制台应用程序崩溃) 这是我的textHandler.cs文件,您可以看到公共静态无效方法WriteInfo正在使用get/set属性,但它使我的应用程序崩溃C# 获取集属性,c#,get,set,C#,Get,Set,因此,我试图在C#上使用get/set属性,但我的代码无法正常工作(这会使我的控制台应用程序崩溃) 这是我的textHandler.cs文件,您可以看到公共静态无效方法WriteInfo正在使用get/set属性,但它使我的应用程序崩溃 class TextHandler { public static void WriteInfo(String text) { var consoleText = new Text(); consoleText.t
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
不需要创建“Text”类。只需将字符串传递给Console.WriteLine。另外,您没有指定应用程序的性质。这在控制台应用程序中可以正常工作,但可能不适用于未绑定到SdtOut的web应用程序或其他应用程序。您需要将“backing”字段与公共属性分开:
public class Text
{
private string text;
public String TheText
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
}
在上面的示例中,text
是一个“名称不正确”的公共属性,text
是支持字段。目前,您的代码正在为这两个字段寻址相同的字段,从而导致递归。通常惯例是使用大写属性Text
和小写支持字段Text
但是,在您的代码中,您将类命名为Text
,因此地址Text.Text
so会让人感到困惑,
您正在将设置为再次调用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; }
}
是的,还有,OP甚至不应该上这门课。为什么要创建一个单独的类来保存一个字符串呢?是的,你说的是有效的,但是我从来没有显示字符串文本,我只是得到了“ServerApp.text”(ServerApp是名称空间)。你知道吗?可能是属性名文本不太好,你可以对它进行更改。在您的情况下,这样做就足够了:ServerApp.text t=new Server.App.text();text.text..是的,您所说的是有效的,但我从未显示字符串文本,我只是得到“ServerApp.text”(ServerApp是名称空间)知道吗?要获得您需要的值:
Console.WriteLine(consoleText.TheText)代码>。这将获取该值。