静态变量与参数传递
抱歉,无法将其表述为适当的标题。 我想知道静态字段与不断传递直到到达目的地的参数相比有什么好处。
示例:
Xna 在其框架中使用 GameTime,它不断被传递到 Update 函数中的子函数中,
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
world.Update(gameTime);
}
//in World class
public void Update(GameTime gametime)
{
//draw all game objects
for (int i = 0; i < entities.Count; i++)
{
entities[i].Update(gametime);
}
}
与在某处保留静态变量 gametime、在执行其他操作之前在根类中更新它并访问相比,这样做有什么好处吗?来自子类的静态变量。
我总是看到库中使用参数传递。但将其静态放置在某处似乎更“方便”。
Couldn't phrase this into a proper title, sorry.
I'm wondering what the benefit is of a static field vs an argument that you keep passing until it reaches it's destination.
Example:
Xna uses GameTime in their framework, which is kept being passed into child functions in the Update function
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
world.Update(gameTime);
}
//in World class
public void Update(GameTime gametime)
{
//draw all game objects
for (int i = 0; i < entities.Count; i++)
{
entities[i].Update(gametime);
}
}
Is there any benefit to doing this, as opposed to keeping a static variable gametime somewhere, updating that in the root class before anything else and access that static variable from the child classes.
I always see the argument passing being used in libraries. But it seems so much more "convenient" to just have it static somewhere.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该静态字段与该类的所有实例共享。除非仔细控制,否则静态和可变会形成危险的混合物。您不希望任何人都接触该字段,除非所有实例都需要更改。
This static field is shared with all instances of the class. Static and mutable provide a dangerous mixture unless it's carefully controlled. You don't want just anyone reaching out and touching that field unless it is essential that ALL instances need the change.
当您注入参数时,您的方法可以更容易地测试。例如,您可以有一个假的 GameTime 对象,您可以传入该对象来模拟它的行为。
And your method can be tested easier when you inject parameters. You could for example have a fake GameTime object which you could pass in to simulate it's behavior.