2016-07-11 4 views
-3

죄송합니다. 방금 내 포인트를 얻으려고 뭔가를 썼습니다. 나는 CONST이있는 경우C# sizeof (상수)가 정의되지 않은 이유

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace CacheScratch 
{ 
    class Class1 
    { 
     public const int a = 0xABAC; 

     int test() 
     { 
      return sizeof(a); 
     } 
    } 
} 

, 왜 내가 오류합니까 : 여기

실제 예제 코드입니다 심각도 코드 설명 프로젝트 파일 라인 억제 상태 오류 CS0233을 '이'는이 없습니다 미리 정의 된 크기이므로 sizeof는 안전하지 않은 컨텍스트에서만 사용할 수 있습니다 (System.Runtime.InteropServices.Marshal.SizeOf 사용을 고려하십시오)

왜 고정 크기 변수에 마샬링이 필요합니까?

+0

코드가 컴파일되지 않았습니다. 존재하지 않는 변수를 참조하고 있습니다. 형식 인수를 사용하지 않고 '0xA4B4'가 짧은 값에 들어 가지 않습니다. –

+1

https://msdn.microsoft.com/en-us/library/eahchzkf(v=vs.120).aspx –

+7

sizeof는 C#에서 임의의식이 아닌 형식을 취합니다. –

답변

1

MSDN: sizeof (C# Reference)에서

For all other types, including structs, the sizeof operator can be used only in unsafe code blocks. Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding.

Used to obtain the size in bytes for an unmanaged type****

확율은 당신이 무슨 일을하는지 된 관리 유형에 대한 크기를 바이트 단위로 받아야 할 이유가 정말이 없다고합니다.

"고정 크기 변수에는 마샬이 필요합니까?"

찾고있는 것이 전부라면 로컬 변수의 크기 일 필요는 없습니다. var size = sizeof(int) 또는 sizeof(short) 으로 전화하면 각각 4 및/또는 2가 반환됩니다.

+0

제 아이디어는 가독성을 위해 고정 크기 변수에 sizeof()를 사용할 수 있다는 것입니다. 분명히 아닙니다. – gismo