2013-02-09 71 views
4

我想这是C#版本翻译一些食人魔代码,我遇到了一个问题:在C#中C++ const size_t的等价物是什么?

const size_t nVertices = 8; 
    const size_t vbufCount = 3*2*nVertices; 

    float vertices[vbufCount] = { 
      -100.0,100.0,-100.0,  //0 position 
      -sqrt13,sqrt13,-sqrt13,  //0 normal 
      //... 
      -sqrt13,-sqrt13,sqrt13,  //7 normal 
    }; 

基本上,常量为size_t并不在C#中存在,const int的,不能用来声明数组的大小。

我想知道如何声明具有常量值的数组?

+2

您不需要显式编写数组的大小,至少不用C++。 – leemes 2013-02-09 13:09:50

+0

数组已经固定,所以没有必要根据常量来设置其大小。 – David 2013-02-09 13:10:05

回答

1
float[] array = new float[] { 1.2F, 2.3F, 3.4F, 4.5F }; 

该如何在C#声明arrays

+1

那么,这是一种方法。你也可以用不同的方式写它,包括float [] array = {1.2F,2.3F,3.4F,4。5F};' – svick 2013-02-09 13:24:25

4

为size_t是一个typedef(有点像#define宏),这基本上是另一种类型的别名。它的定义取决于SDK,但通常是unsigned int

不管怎样,在这种情况下,因为他们是常数,所以你知道nVertices是8和vbufCount是48.你可以只写它像这样在C#中它并不真正的问题:

const int nVertices = 8; 
const int vbufCount = 3 * 2 * nVertices; 

float[] vertices = new float[vbufCount] { 
    -100.0,100.0,-100.0,  //0 position 
    -sqrt13,sqrt13,-sqrt13,  //0 normal 
    //... 
    -sqrt13,-sqrt13,sqrt13,  //7 normal 
    }; 
+2

顺便说一句,这将不会编译,因为'100.0'是'double',它不能隐式转换为'float'。你可以通过使用'f'后缀:'100.0f'来解决这个问题。 – svick 2013-02-09 13:33:38

2

基本上,const size_t在C#中不存在,并且const int不能用于声明数组的大小。

这不是因为const int,而是因为数组大小不是C#中数组类型的一部分。你可以改变你的代码如下:

float[] vertices = { 
     -100.0f,100.0f,-100.0f,  //0 position 
     -sqrt13,sqrt13,-sqrt13,  //0 normal 
     //... 
     -sqrt13,-sqrt13,sqrt13,  //7 normal 
}; 

还有其他几种方法可以做同样的事情,包括:

const int nVertices = 8; 
const int vbufCount = 3*2*nVertices; 

float[] vertices = new float[vbufCount] { 
     -100.0f,100.0f,-100.0f,  //0 position 
     -sqrt13,sqrt13,-sqrt13,  //0 normal 
     //... 
     -sqrt13,-sqrt13,sqrt13,  //7 normal 
}; 

唯一的区别是,如果项目在初始化的数量没有按与您指定的数字不匹配,您将收到编译时错误。

1

在C++中,size_t是一个至少16位的无符号整数类型,它遵循CPU的本地整数类型。换句话说,sizeof(size_t)不是固定的,即使大多数人将它用作'unsigned int'。在C#中没有这样的事情。

C#中的大小(使用数组和列表时的f.ex.)通常是一个32位整型的“int”类型。

在你的情况,我可能会做阵列只读和使用“vertices.Length”,如:

private readonly float[] vertices = new float[] 
    { 
     1f,2f,3f,4f,5.2f // etc 
    }; 

或在这种情况下,我可能把它定义为一个二维数组,并使用vertices.GetLength :

private readonly float[,] vertices = new float[5,5]; 

    // fill in code: 
    vertices[0, 0] = 0; 
    // etc 
1

所有这些答案都没有真正回答什么类型等同于size_t的问题。 .NET中size_t的正确类型是UIntPtr。它在32位平台上是32位,在64位平台上是64位,并且没有签名。这是唯一真正相同的类型。

相关问题