[英]Structure is an value type, Then why don't compiler gives any error when string is declared within struct
為什么即使字符串是引用類型,下面編寫的代碼也不會給出錯誤。
public struct example
{
public int a;
public string name;
};
public void usestruct()
{
example objExample= new example();
MessageBox.Show(objExample.name);
}
編輯
修改喬恩答案,我還有幾個問題。
public struct Example
{
public int a;
public string name;
}
class Test
{
static void Main()
{
//Question 1
Example t1 = new Example();
t1.name = "First name";
Example t2 = t1;
t2.name = "Second name";
Console.WriteLine(t1.name); // Prints "First name"
Console.WriteLine(t2.name); // Prints "Second name"
Console.WriteLine(t1.name); // What will it Print ????
//Question 2
Example t1 = new Example();
t1.name = "First name";
Console.WriteLine(sizeof(t1)); // What will it Print ????
// I think it will print 4 + 4 bytes.
//4 for storing int, 4 for storing address of string reference.
//Considering
//int of 4 bytes
//Memory Address of 4 byte
//Character of 1 byte each.
//My collegue says it will take 4+10 bytes
//i.e. 4 for storing int, 10 bytes for storing string.
}
}
第二種情況將占用多少字節。
該結構僅包含對字符串的引用。 為什么會引起問題? 引用只是一個值。 當您復制結構的值(例如,賦值或將其傳遞給方法)時,引用也將被復制。 請注意,如果您在結構的一個副本中更改該字段的值,則不會在另一副本中更改該值:
using System;
public struct Example
{
public int a;
public string name;
}
class Test
{
static void Main()
{
Example t1 = new Example();
t1.name = "First name";
Example t2 = t1;
t2.name = "Second name";
Console.WriteLine(t1.name); // Prints "First name"
Console.WriteLine(t2.name); // Prints "Second name"
}
}
如果Example
是一個類,則它們都將打印“ Second name”,因為t1
和t2
的值將引用同一實例。
這也不是專門針對字符串的-任何引用類型都可以使用。
但是,我強烈建議不要創建可變結構或公開公共領域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.