覆盖静态字段

Overriding static field(覆盖静态字段)
本文介绍了覆盖静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的游戏编写 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.

这是我目前正在做的:

块.cs

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

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.
  • 不必每次访问属性时都创建一个新矩形

推荐答案

静态成员不会被多态调用——就这么简单.请注意,您谈论的是 保持 静态属性 - 目前您没有 静态属性.您有一个实例属性和两个静态 字段.

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.

几个选项:

  • 在每个类中被覆盖的虚拟成员,即使它不需要对象的任何状态(除了其类型)
  • 将要绘制的矩形传入块的构造函数中,并将其存储在一个字段中

这篇关于覆盖静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)