首页 \ 问答 \ C#与结构内的列表混淆(值类型与引用类型)(C# Confused with a list inside a struct (value type vs reference type))

C#与结构内的列表混淆(值类型与引用类型)(C# Confused with a list inside a struct (value type vs reference type))

所以今天我发现当用于在C#中赋值变量时,结构和类的行为有所不同。据我所知,当我将一个结构赋给变量时,变量存储该结构的副本,当我分配一个类时对于变量,变量存储对该类实例的引用。

在这种情况下,dad2包含一个dad1的副本,所以我不应该对dad2做什么不影响dad1? 事实并非如此,因为当我向dad2添加一个儿子时,它也会向dad1添加相同的儿子。

public struct Dad {
        public string name;
        public List <Son> sons;

        public struct Son {
            public string name;

            public Son (string n) {
                name = n;
            }
        }
    }

    static void Main (string [] args) {
        Dad dad1 = new Dad ();
        dad1.name = "Bob";
        dad1.sons = new List <Dad.Son> {new Dad.Son ("A")};

        Dad dad2 = dad1;
        Debug.WriteLine (dad2.Equals (dad1) + " " + dad1.sons.Count () + " " + dad2.sons.Count ());
        //true 1 1
        dad2.sons.Add ( new Dad.Son ("B"));
        Debug.WriteLine (dad2.Equals (dad1) + " " + dad1.sons.Count () + " " + dad2.sons.Count ());
        //true 2 2
    }

So I found out today that structs and classes act differently when used to assign to variables in C#.. It's to my understanding that when I assign a struct to a variable, the variable stores a copy of that struct, and when I assign a class to a variable, the variable stores the reference to that class instance.

In this case, dad2 contains a copy of dad1, so shouldn't anything I do to dad2 not affect dad1? It's not the case apparently because when I add a son to dad2 it also adds the same son to dad1.

public struct Dad {
        public string name;
        public List <Son> sons;

        public struct Son {
            public string name;

            public Son (string n) {
                name = n;
            }
        }
    }

    static void Main (string [] args) {
        Dad dad1 = new Dad ();
        dad1.name = "Bob";
        dad1.sons = new List <Dad.Son> {new Dad.Son ("A")};

        Dad dad2 = dad1;
        Debug.WriteLine (dad2.Equals (dad1) + " " + dad1.sons.Count () + " " + dad2.sons.Count ());
        //true 1 1
        dad2.sons.Add ( new Dad.Son ("B"));
        Debug.WriteLine (dad2.Equals (dad1) + " " + dad1.sons.Count () + " " + dad2.sons.Count ());
        //true 2 2
    }

原文:https://stackoverflow.com/questions/6811447
更新时间:2022-03-18 22:03

最满意答案

还存在其他可能性。 您可以尝试使用RewriteRule中的“(。*)”更改所有特殊字符。


Also exist other posibility. You can try to change all special characters with this "(.*)" in the RewriteRule.

相关问答

更多
  • 您不必在JS字符串中执行任何特殊编码(除了可能被视为脚本元素关闭的字符串的特殊情况)。 如果您的JS文件编码与HTTP标头(最常见的是UTF-8)匹配,那么只要您这样做就会解码 var my_special_char = 'ñ'; my_div.innerHTML = my_special_char; 为了帮助浏览器,并假设您正确地使用相关的HTTP标头(它的设置方式高度依赖于您的服务器)提供文件,您应该在HTML标头中包含此元标记: 如果您的脚本位于单独的 ...
  • 首先,请注意,重新启动httpd对于.htaccess文件是不必要的。 .htaccess文件专门针对没有root权限的用户,即无法访问httpd服务器配置文件,无法重新启动服务器。 当您可以重新启动服务器时,您不需要.htaccess文件,可以直接使用主服务器配置。 其次,如果.htaccess文件被忽略,则需要检查以确保AllowOverride设置正确。 有关详细信息,请参见http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride 。 您 ...
  • 这个变音符号实际上被称为短语,在许多东欧语言中很常见。 我曾经遇到同样的问题。 我在这里甚至有一个问题。 由于没有人解决这个问题,所以值得一试...... 这还不清楚: 它只发生在这个项目上吗? 你尝试别人吗? (也许是项目错误) 尝试包括其他语言文件夹(尝试,比如values-fr)。 你有同样的问题吗? 您是否尝试在Eclipse内部构建应用程序? 您是否尝试在命令行上手动构建? 然后,你可以尝试: 而不是“ó”(在PT中我们使用相同的),请尝试\u00f3 。 像: Versi\u00f3n 。 你是 ...
  • 如果您使用的是Linux服务器,则可以在hosts文件中实现相同的功能。 您需要在主机配置文件中定义相同的规则。 you can achieve same thing in hosts file if you are using Linux server. you need to define same rules in hosts configuration file.
  • 问题是当cgi-bin存在于htdocs之外时, htdocs .htaccess文件永远不会运行,因为它只适用于包含它及其子目录的目录。 将cgi-bin RewriteRule放在cgi-bin中的.htaccess文件中。 The problem is that when cgi-bin exists outside htdocs, the htdocs .htaccess file never runs, as it only applies to the directory that contai ...
  • 好。 我在javac和javadoc ant任务中使用encoding =“iso-8859-15”解决了它,以强制它应该使用的字符编码。 Ok. I solved it using encoding="iso-8859-15" in javac and javadoc ant tasks, in order to force the character encoding it should use.
  • 为什么不? 您可以使用bin/mahout脚本的seq2sparse命令,并使用-a选项指定相应的Lucene分析器( org.apache.lucene.analysis.es.SpanishAnalyzer )。 参见Mahout in Action一书的第8章(第199-200页......)。 除此之外,您还可以使用现有的分析仪编写自己的分析仪。 本书包含许多示例,您可以在存储库中找到源代码。 Why not? You can use seq2sparse command of bin/mahout ...
  • 还存在其他可能性。 您可以尝试使用RewriteRule中的“(。*)”更改所有特殊字符。 Also exist other posibility. You can try to change all special characters with this "(.*)" in the RewriteRule.
  • 你已经触及了charsets的精细主题。 尝试创建并将所有内容转换为utf-8。 数据库,文件,表格等。 在互联网上查找有关在电子邮件中使用哪个标头以使其成为utf-8的一些信息。 还可以使用这些标头将您的电子邮件从标准的7位转换为8位。 "Content-Type: text/plain; charset=utf-8" "Content-Transfer-Encoding: 8bit" 对于数据库,您需要在mysql的情况下设置排序规则。 You have touched the fine subjec ...
  • \p{L}匹配一个unicode字母(与任何符号相对),是最佳选择。 但是,你肯定发现它没有(总是)匹配重音字母。 这是因为在unicode中,重音字母有时可以表示为两个字符:没有重音的字母,后面是代表重音的组合标记。 匹配这些的类是\p{M} ,它给了我们以下代码(考虑你说你想要包含空格的注释): if(text.matches("(?:\\p{L}\\p{M}*\\s*)+")) { System.out.println("Muy bien !"); } 更多信息在这里 。 \p{L} matches ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)