繁体   English   中英

结构是一个值类型,那么当在结构体中声明字符串时,为什么编译器不给出任何错误

[英]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”,因为t1t2的值将引用同一实例。

这也不是专门针对字符串的-任何引用类型都可以使用。

但是,我强烈建议不要创建可变结构或公开公共领域。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM