gpt4 book ai didi

c# - 静态变量不变

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:13 25 4
gpt4 key购买 nike

我有一个项目分为 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);
}
}
}

我可以在Console项目中改值就好了,我的console输出library项目中的LastSaid变量变了,但是当我最后要在我的游戏项目中输出LastSaid变量时,它根本没有变当我检查变量时,它保持在实例化时的值。谁能帮我解释一下为什么会这样?

最佳答案

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

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

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

关于c# - 静态变量不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com