覆盖静态场 [英] Overriding static field

查看:54
本文介绍了覆盖静态场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为自己的游戏编写C#游戏引擎,但遇到了问题.

I'm writing a C# game engine for my game, and I've hit a problem.

我需要为每种不同类型的块做一个XNA.Rectangle drawRectangle.

I need to do a XNA.Rectangle drawRectangle for each different type of block.

块存储在块列表中,因此必须覆盖可以通过绘制访问而无需大量投放的属性.

Blocks are stored in a list of blocks, so the property, to be accessible by draw without casting a lot, must be overriden.

我尝试了很多方法,但是没有用.

I've tried lots of ways of doing it, but none work.

这是我目前正在做的事情:

Here's the current one I'm doing:

Block.cs

protected static Rectangle m_drawRectangle = new Rectangle(0, 0, 32, 32);
public Rectangle drawRectangle
{
    get { return m_drawRectangle; }
}

BlockX.cs

BlockX.cs

protected static Rectangle m_drawRectangle = new Rectangle(32, 0, 32, 32);

但是,当创建BlockX并访问drawRectangle时,它仍然返回0、0、32、32.

However when creating BlockX and accessing drawRectangle, it still returns 0, 0, 32, 32.

理想情况下,我可以覆盖drawRectangle成员,但是这样做将意味着在每个单独的块类中创建一个成员.我只想调整m_drawRectangle.

Ideally I could just override the drawRectangle member, however doing this would mean creating a member in every single block class. I only want to adjust m_drawRectangle.

每个块都会被创建数百次,所以我不希望它是非静态的,并且在构造函数中执行它是很愚蠢的.

Each block will be created hundreds of times so I don't want it to be non-static, and it would be silly to do it in the constructor.

除了在每个块中放置静态函数以初始化静态事物之外,还有其他更好的方法吗?

Is there any better way other than just putting a static function to initialise static things in every block?

总而言之,我的要求是:

So to sum up, my requirements are:

  • BlockX.cs中要覆盖的最少的额外代码
  • 字段必须保持静态
  • 最好不必覆盖drawRectangle,而只需覆盖m_drawRectangle.
  • 不必每次访问属性都创建一个新的矩形
  • Minimal extra code in BlockX.cs to override
  • Field must stay static
  • Preferably not have to override drawRectangle, only m_drawRectangle.
  • Not having to create a new rectangle every time the property is accessed

推荐答案

静态成员不是多态调用的,就这么简单.请注意,您谈论的是保持静态属性-您暂时没有 静态属性.您有一个instance属性,并且有两个静态 fields .

Statics members aren't called polymorphically - it's as simple as that. Note that you talk about the property staying static - you don't have a static property at the moment. You have an instance property, and two static fields.

几个选项:

  • 在每个类中被重写的虚拟成员,即使它不需要对象的状态(类型除外)
  • 传递矩形以绘制块的构造函数,并将其存储在字段中

这篇关于覆盖静态场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆