【问题标题】:static variable not changing静态变量不变
【发布时间】:2018-07-29 23:26:33
【问题描述】:

我有一个项目,它分为 3 个单独的 Visual Studio 项目,一个游戏、控制台和库项目,我试图从库中获取一个静态变量以从我的控制台项目中更改,然后在游戏项目中读取它.这里有一些代码可以清除它:

这是我的库代码,我要更改的一个变量

namespace LibraryProject.Values
{
    public class Variables
    {
        public static string LastSaid { get; set; }
    }
}

这是控制台项目,我在库项目中更改了这个字符串:

namespace ConsoleProject
{
        private void Client_OnMessageRecieved(object sender, OnMessageReceivedArgs e)
        {
            Console.WriteLine("Recieved message, the message was: " + e.ChatMessage.Message);
            Variables.LastSaid = e.ChatMessage.Message;
            Console.WriteLine("LastSaid is now: " + Variables.LastSaid);
        }
}

最后这是我的游戏项目,它在屏幕上显示值。

namespace LibraryProject
{
    public Interface(ContentManager content)
    {
    TextString lastSaid;


        public void Update()
        {
            lastSaid = new TextString(fonts.Font1, Variables.LastSaid, new Vector2(100, 100), Color.White);
        }
}

我的 TextString 类:

namespace LibraryProject
{
    class TextString
    {
        SpriteFont Font;
        string Text;
        Vector2 Position;
        Color Color;

        public TextString(SpriteFont font, string text, Vector2 position, Color color)
        {
            this.Font = font;
            this.Text = text;
            this.Position = position;
            this.Color = color;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            if (Text != null)
            {
                spriteBatch.DrawString(Font, Text, Position, Color);
            }
        }
    }
}

我的游戏项目:

namespace GameProject
{
    public class GameCore : Game
    {
        protected override void LoadContent()
        {
            Interface = new Interface(Content);
        }
        protected override void Update()
        {

            Interface.Update(gameTime);
}
}
}

我可以在控制台项目中更改值就好了,我的控制台输出库项目中的LastSaid变量已经改变,但是当我最终想在我的游戏项目中输出LastSaid变量时,它根本没有改变当我检查变量时,它保持在它被实例化的值。谁能帮我解释一下为什么会这样?

【问题讨论】:

  • 创建类static
  • 向我们展示您的实际代码。 lastSaid 不存在。
  • 试试LibraryProject.Variables.LastSaid(使用完整的命名空间)
  • 在尝试之前确保值为set,并在设置get 之前确保值是Update
  • 您的游戏项目是否与控制台和库项目在同一进程中运行?

标签: c# monogame


【解决方案1】:

我假设您的 GameProject 和 ConsoleProject 是两个应用程序。

如果是这种情况,静态变量不会在两个进程之间共享,它们都有一个内存实例。即使静态变量属于某个库。

其他问答类似: Static members behavior with multiple instance of application - C#

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2016-05-19
    • 2020-07-13
    • 1970-01-01
    相关资源
    最近更新 更多