1 If the values are equal, the objects will be equal by default?
What are the default rules for determining the existence of a reference type in a .net container? Determine whether pointer values are equal.
private static List<int> list; static void Main(string[] args) { //新建实例instance1 MyObject instance1 = new MyObject(); instance1.Value = 10; //新建list List<MyObject> list = new List<MyObject>(); //引用实例instance1 list.Add(instance1); //新建实例:instance2 MyObject instance2 = new MyObject(); //赋值为instance1.Value instance2.Value = instance1.Value; } }
Model class used:
public class MyObject { public int Value { get; set; } }
Let’s do a test below:
//即便Value相等,instance2与instance1的内存地址不相等! bool isExistence1 = list.Contains(instance2); //isExistence1 : false;
The result of this test is false because they point to different Memory address, although the values are equal, this is the "values are equal, objects are not equal" situation.
If a reference type wants to determine whether it is equal based on one of its attribute values, then it needs to implement the IEquatable interface!
If you want to continue to see whether the objects are equal based on whether the values are equal, please refer to the article: C# container, interface class, performance
2 Reference trap?
One object refers to another object. When one changes, the other changes. For example, when merging two dictionaries, the merge result is correct, but the original object is accidentally changed.
Here is an example:
var dict1 = new Dictionary<string, List<string>>(); dict1.Add("qaz",new List<string>(){"100"});//含有qaz键 dict1.Add("wsx",new List<string>(){"13"}); var dict2 = new Dictionary<string, List<string>>(); dict2.Add("qaz", new List<string>() { "11" });//也含有qaz键 dict2.Add("edc", new List<string>() { "17" }); //合并2个字典到dict var dictCombine = new Dictionary<string, List<string>>(); foreach (var ele in dict1) //拿到dict1 { dictCombine .Add(ele.Key,ele.Value); } foreach (var ele in dict2) //拿到dict2 { if(dictCombine.ContainsKey(ele.Key))//检查重复 dictCombine [ele.Key].AddRange(ele.Value); else { dictCombine .Add(ele.Key,ele.Value); } }
The result of dictCombine is correct, {"qaz", "100" and "11"}, {"wsx" ","13"},{"edc","17"}
But what about the result of dict1? Been changed! dict1 unexpectedly became {"qaz", "100" and "11"}, {"wsx", "13"}. Correct merge, dict1 should not be changed!
Analysis of reasons
dictCombine first adds the key value of dict1, that is, the key values of dictCombine all refer to the key value of dict1; Next, When merging dict2, first determine whether dictCombine contains the key of dict2. If it does, add it to the key value of dictCombine. The value refers to the same object, that is, this value is added to the key of dict1. Verification of whether dictCombine[ele.Key] and dict1[ele.Key] references are equal:
bool flag = object.ReferenceEquals(dictCombine[ele.Key], dict1[ele.Key]);//true
Correct solution
Avoid dictCombine[ele.Key] and dict1[ele .Key] reference equality! ! !
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); //先把键都合并到dictCombine中,值都是新创建的 foreach (var key in dict1.Keys) { if (!dictCombine.ContainsKey(key)) dictCombine.Add(key, new List<string>()); } foreach (var key in dict2.Keys) { if (!dictCombine.ContainsKey(key)) dictCombine.Add(key, new List<string>()); } //分别将值添加进去 foreach (var ele in dict1) { dictCombine[ele.Key].AddRange(ele.Value); } foreach (var ele in dict2) { dictCombine[ele.Key].AddRange(ele.Value); }
dictCombine merge result is correct, and neither dict1 nor dict2 has changed!
Summary
Using reference equality brings many benefits, such as reference-to-value (by reference) between functions. However, if used improperly, it will also bring us some unnecessary trouble.
#3 Improper reference destroys encapsulation?
If you use the private field in the encapsulated class as the return value of the interface method, this approach will destroy the encapsulation of the class, especially An issue that is easily overlooked. If you ignore this issue, inexplicable problems may occur.
As shown in the following code,
public class TestPrivateEncapsulate { private List<object> _refObjs; public List<object> GetRefObjs() { _refObjs = new List<object>(); ... ... //其他逻辑处理计算出来的_refObjs={1,4,2}; return _refObjs; //返回私有字段 } public object GetSumByIterRefObjs() { if (_refObjs == null) return null; foreach (var item in _refObjs) { ...//处理逻辑 } } }
Now using the class TestPrivateEncapsulate just written, we first create an instance,
TestPrivateEncapsulate test = new TestPrivateEncapsulate();
And then call:
List<object> wantedObjs = test.GetRefObjs();
The expected wantedObjs returned should have 3 elements of integer type, 1, 4, 2.
Continue:
List<object> sol = wantedObjs; //我们将sol指向wantedObjssol.Add(5); //加入元素5
When we want to go back and calculate, the original sum of elements of wantedObjs:
test.GetSum();
We accidentally got 12, not 7 as expected. Why is this?
After careful analysis, we found that after calling sol.Add(5) on the client, we indirectly modified the variable in TestPrivateEncapsulate: _refObjs, which was changed from {1,4,2} to {1,4 ,2,5}.
Private variables were modified on the client side! This is the side effect of the interface returning private variables!
Correct answer:
// 将原来的公有变为私有 private List<object> getRefObjs() { _refObjs = new List<object>(); ... ... //其他逻辑处理计算出来的_refObjs={1,4,2}; return _refObjs; //返回私有字段 } //只带只读的属性 public RefObjs { get { getRefObjs(); return _refObjs; } }
Set a public field with only read-only attributes, and change the original public method GetRefObjs into the private method getRefObjs, so that in It is impossible for the client to modify private fields!
Summarize
The attribute values of the objects are all equal, but the object references are not necessarily equal;
Two or more objects refer to an object. If this object is modified, the attribute values of all referrers are also modified;
Member return Encapsulated reference variables will destroy the encapsulation.
The above is the detailed introduction of the three thoughts of C#reference. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

如何使用C#编写时间序列预测算法时间序列预测是一种通过分析过去的数据来预测未来数据趋势的方法。它在很多领域,如金融、销售和天气预报中有广泛的应用。在本文中,我们将介绍如何使用C#编写时间序列预测算法,并附上具体的代码示例。数据准备在进行时间序列预测之前,首先需要准备好数据。一般来说,时间序列数据应该具有足够的长度,并且是按照时间顺序排列的。你可以从数据库或者

如何使用Redis和C#开发分布式事务功能引言分布式系统的开发中,事务处理是一项非常重要的功能。事务处理能够保证在分布式系统中的一系列操作要么全部成功,要么全部回滚。Redis是一种高性能的键值存储数据库,而C#是一种广泛应用于开发分布式系统的编程语言。本文将介绍如何使用Redis和C#来实现分布式事务功能,并提供具体代码示例。I.Redis事务Redis

如何实现C#中的人脸识别算法人脸识别算法是计算机视觉领域中的一个重要研究方向,它可以用于识别和验证人脸,广泛应用于安全监控、人脸支付、人脸解锁等领域。在本文中,我们将介绍如何使用C#来实现人脸识别算法,并提供具体的代码示例。实现人脸识别算法的第一步是获取图像数据。在C#中,我们可以使用EmguCV库(OpenCV的C#封装)来处理图像。首先,我们需要在项目

如何使用C#编写动态规划算法摘要:动态规划是求解最优化问题的一种常用算法,适用于多种场景。本文将介绍如何使用C#编写动态规划算法,并提供具体的代码示例。一、什么是动态规划算法动态规划(DynamicProgramming,简称DP)是一种用来求解具有重叠子问题和最优子结构性质的问题的算法思想。动态规划将问题分解成若干个子问题来求解,通过记录每个子问题的解,

Redis在C#开发中的应用:如何实现高效的缓存更新引言:在Web开发中,缓存是提高系统性能的常用手段之一。而Redis作为一款高性能的Key-Value存储系统,能够提供快速的缓存操作,为我们的应用带来了不少便利。本文将介绍如何在C#开发中使用Redis,实现高效的缓存更新。Redis的安装与配置在开始之前,我们需要先安装Redis并进行相应的配置。你可以

C#开发中如何处理跨域请求和安全性问题在现代的网络应用开发中,跨域请求和安全性问题是开发人员经常面临的挑战。为了提供更好的用户体验和功能,应用程序经常需要与其他域或服务器进行交互。然而,浏览器的同源策略导致了这些跨域请求被阻止,因此需要采取一些措施来处理跨域请求。同时,为了保证数据的安全性,开发人员还需要考虑一些安全性问题。本文将探讨C#开发中如何处理跨域请

如何实现C#中的图像压缩算法摘要:图像压缩是图像处理领域中的一个重要研究方向,本文将介绍在C#中实现图像压缩的算法,并给出相应的代码示例。引言:随着数字图像的广泛应用,图像压缩成为了图像处理中的重要环节。压缩能够减小存储空间和传输带宽,并能提高图像处理的效率。在C#语言中,我们可以通过使用各种图像压缩算法来实现对图像的压缩。本文将介绍两种常见的图像压缩算法:

如何在C#中实现遗传算法引言:遗传算法是一种模拟自然选择和基因遗传机制的优化算法,其主要思想是通过模拟生物进化的过程来搜索最优解。在计算机科学领域,遗传算法被广泛应用于优化问题的解决,例如机器学习、参数优化、组合优化等。本文将介绍如何在C#中实现遗传算法,并提供具体的代码示例。一、遗传算法的基本原理遗传算法通过使用编码表示解空间中的候选解,并利用选择、交叉和


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
