24 Aralık 2017 Pazar

sizeof Anahtar Kelimesi

Giriş
Açıklaması şöyle
Used to obtain the size in bytes for an unmanaged type. Unmanaged types include the built-in types that are listed in the table that follows, and also the following:
Enum types
Pointer types
User-defined structs that do not contain any fields or properties that are reference types
Class İçin Kullanılamaz
Class için Unsafe.Sizeof() kullanılır.
Örnek
Metodun unsafe olarak işaretli olması gerekir. Görmek için şöyle yaparız.
public struct Test {
  public int Int1;
}

static void Main() {
  // works
  var s1 = Unsafe.SizeOf<Test>();
  // doesn't work, need to mark method with "unsafe"
  var s2 = sizeof(Test);            
}
unsafe olarak işaretli olsa bile çalışmaz. Görmek için şöyle yaparız.
public struct Test {
  public int Int1;
  public string String1;
}


static unsafe void Main() {
  // works, return 16 in 64bit process - 4 for int, 4 for padding, because
  // alignment of the type is the size of its largest element, which is 8
  // and 8 for string
  var s1 = Unsafe.SizeOf<Test>();
  // doesn't work even with unsafe, 
  // cannot take size of variable of managed type "Test"
  // because Test contains field of reference type (string)
  var s2 = sizeof(Test);                        
} 

Hiç yorum yok:

Yorum Gönder