【问题标题】:Constant based on variable?基于变量的常量?
【发布时间】:2011-04-29 17:53:47
【问题描述】:

我现在正在 XNA 中制作一个小游戏。

我想根据我的屏幕分辨率来确定数组的大小。

我是这样做的:

public const int intBoardheight = (GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height -150) / 10 ;
public const int intBoardwidth = (GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width - 200) / 10;

public bool[,] GameBoard = new bool[intBoardheight,intBoardwidth];
public bool[,] GameBoardUpdate = new bool[intBoardheight, intBoardwidth];
public int[,] GameBoardInt = new int[intBoardheight, intBoardwidth];

但这给了我错误“分配给'Game_Of_Life_2.Game1.intBoardheight'的表达式必须是常数”。

那么,如何将常量基于变量?

提前致谢!

西蒙。

编辑: 多谢你们!效果很好!

【问题讨论】:

  • 常量是从不改变的东西。不是在程序生命周期中永远不会改变的东西。 永远就像“在过去、现在或未来的任何时间点,这个值都不会是任何与这里所说的不同。” Pi 是一个常数。 1 是一个常数。 CurrentDisplayMode.Height 不是常数。
  • 嗯,如果你基于一个变量,它就是一个变量。

标签: c# arrays variables xna constants


【解决方案1】:

你不能。将其设为public static readonly int

【讨论】:

  • 我投赞成票,我认为 static readonly 比 readonly 更好地表达了“常量”的概念(可以由每个类实例在其构造函数中更改)。
【解决方案2】:

您不能创建常量,但可以将其设为只读

public readonly int intBoardheight = ...

readonly 变量只能在声明或构造函数中赋值。之后就无法更改了。

【讨论】:

    【解决方案3】:

    因为它是可变的 - 基于当前分辨率当你运行你的应用程序 - 你不能让它成为编译时间常数,但你可以让它 readonly

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 2014-01-30
      • 2012-05-30
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多