使用字节将"256"作为参数传递的解决方法

Kyl*_*ran 0 c# arrays byte

我正在创建一个包含私有数组的类,我用它来缓存计算值.我想将元素数量限制为最多256个,因为这是使用byte索引的索引器可以访问的元素的最大数量; 我还需要数字相当小,所以这是有效的.

然而!它必须作为构造函数中的参数传递,因为客户端代码将确定它有多大.但是,如果我以a byte为参数,最大值为255; 我理解为什么以及如何,但我无法找出最好的解决方法.

public class Spritesheet
{
    private Rectangle[] _values;
    public Spritesheet(byte spriteCount)
    {
        _values = new Rectangle[spriteCount]; // But this needs to store 256 values at most...
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以把它变成一个字节?如果它是null,则使用256个元素,但这似乎是任意的(虽然它肯定会起作用).我可以看到的另一个替代方法是使用int并以某种方式限制值,但是将其暴露为int可能会给用户错误的代码意图.

编辑:将"spritesToIndex"更改为"spriteCount"以使其更清晰.对于它的价值,这是我正在实现的界面:

public interface ISpritesheet
{
    Texture2D Texture { get; }

    byte Sprites { get; }
    byte SpritesPerRow { get; }

    Point Size { get; }
    Point Spacing { get; }
    Point Offset { get; }

    Rectangle this[byte index] { get; }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

我能看到的另一种选择是使用int并以某种方式钳制值

使用int正是我要做的.

但是将它暴露为int可能会给用户错误的代码意图.

因此,使意图明确,以至于用户不可能得到错误的想法:

public class Spritesheet
{
  public Spritesheet(int spriteCount)
  {
    if (spriteCount < 0 || spriteCount > 256)
      throw new ArgumentOutOfRangeException ("spriteCount", "Number of sprites must be between 0 and 256 (inclusive)");
    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)

即使在任何时候,用户得到的想法,spriteCount可能是1000,这个想法会褪色努力之后很快.

我重新命名为spriteToIndex回应理查德施耐德的评论,他们可以理解地不同地解释变量名的含义.其中的"索引"一词可以理解为表示该值必须是索引,而不是精灵的总数.

  • 在这里明确揭示了一个有趣的结论:这接受257个有效输入,而不是256,因此输入必须大于`byte`.但是,只有在0实际上是合法值的情况下才是这种情况.如果0实际上不合法,那么RichardSchneider的答案的优点是使编译时无法传递非法值. (2认同)