0

所以我试图在 XNA 4.0 win 游戏上制作一个文本框(不完全是一个文本框,只是改变一个 spriteFont 文本)继承我的代码:

usernameVar.Draw(spriteBatch, newInputText);

这将在每一帧绘制 newInputText 字符串

newInputText = username.update(mouse);

这将设置字符串,但这是我的问题

class Textbox
{
    public Texture2D texture;
    public Rectangle rectangle;
    public bool isClicked;

    public Textbox(Texture2D newTexture, Rectangle newRectangle)
    {
        texture = newTexture;
        rectangle = newRectangle;
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, rectangle, Color.White);
    }
    public String update(MouseState mouse)
    {
        Rectangle mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1);
        var textboxText = new newText();

        if (mouseRectangle.Intersects(rectangle))
        {
            isClicked = true;
            if (isClicked)
            {
                textboxText.newtext = "a";
                Connection.sendPacketBool("ae", textboxText.newtext);
                return textboxText.newtext;  
            }
        }

        return null;
    }
}
class newText
{
    public String newtext
    {
        get 
        { 
            return this.newtext; 
        }
        set 
        { 
            this.newtext = value; 
        }
    }
}

这个 textbox.cs 文件首先给了我一些错误,我应该怎么做才能避免返回 IF 语句之外的内容?

public String update(MouseState mouse)
    {
        Rectangle mouseRectangle = new Rectangle(mouse.X, mouse.Y, 1, 1);
        var textboxText = new newText();

        if (mouseRectangle.Intersects(rectangle))
        {
            isClicked = true;
            if (isClicked)
            {
                textboxText.newtext = "a";
                Connection.sendPacketBool("ae", "a");
                return "yo";  
            }
        }

        return null;
    }

由于 return null 打破了我的文本框(我无法将 null 文本添加到 spritefont )另外,如果我删除 return null 添加 return "something" 我在设置属性上收到此错误

An unhandled exception of type 'System.StackOverflowException'

抱歉,我对 C# 和所有这些东西都很陌生,谢谢

4

1 回答 1

3

我不确定您的项目的确切结构,也不确定newText该类的原因,但它包含的属性一遍又一遍地调用自身。

class newText
{
    public String newtext
    {
        get 
        { 
            return this.newtext; //Get newtext again, which gets it again, and again, etc
        }
        set 
        { 
            this.newtext = value; //Set newtext, which calls set again, and again...
        }
    }
}

当你 get 或 setnewtext时,它会一遍又一遍地获取或设置自己,从而导致递归循环。这永远不会结束,并将导致StackOverflowException.

使用属性的正确方法是让公共访问器 ( NewText) 执行逻辑(在这种情况下,只是获取和设置)并返回或设置一个值,在这种情况下,存储变量newText

这是一个例子:

private string newText; //Storage Field

public string Newtext //Accessor
{
    get { return newText; }
    set { newText = value; }
}

C# 3.0 具有自动属性,因此这不是必需的 (:P)。

作为补充说明,您不必使用String类,string并且String相同的东西,但使用string通常是首选方法。

于 2013-07-24T16:07:58.780 回答