[英]Structure is an value type, Then why don't compiler gives any error when string is declared within struct
Why below written code doesn't gives error even when string is a reference type. 为什么即使字符串是引用类型,下面编写的代码也不会给出错误。
public struct example
{
public int a;
public string name;
};
public void usestruct()
{
example objExample= new example();
MessageBox.Show(objExample.name);
}
EDIT 编辑
Modifying Jon Answer, I have few more Questions. 修改乔恩答案,我还有几个问题。
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.
}
}
How many bytes will second case take. 第二种情况将占用多少字节。
The struct just contains a reference to a string. 该结构仅包含对字符串的引用。 Why would that cause a problem? 为什么会引起问题? A reference is just a value. 引用只是一个值。 When you copy the structure's value (eg with assignment, or passing it to a method) the reference will be copied too. 当您复制结构的值(例如,赋值或将其传递给方法)时,引用也将被复制。 Note that if you change the value of the field in one copy of the struct, that won't change the value in a different copy: 请注意,如果您在结构的一个副本中更改该字段的值,则不会在另一副本中更改该值:
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"
}
}
If Example
were a class instead, these would both print "Second name" as the values of t1
and t2
would be references to the same instance. 如果Example
是一个类,则它们都将打印“ Second name”,因为t1
和t2
的值将引用同一实例。
This isn't specific to strings, either - any reference type will work. 这也不是专门针对字符串的-任何引用类型都可以使用。
However, I would strongly advise against creating mutable structs or exposing public fields. 但是,我强烈建议不要创建可变结构或公开公共领域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.