Home Backend Development C#.Net Tutorial .NET Framework-Code example sharing of reference traps

.NET Framework-Code example sharing of reference traps

Mar 18, 2017 pm 01:39 PM

1 If the values ​​are equal, 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;       
        }
    }
Copy after login

The Model class used:

            public class MyObject
            {
                public int Value { get; set; }
            }
Copy after login

Let’s do a test below:

            //即便Value相等,instance2与instance1的内存地址不相等!
            bool isExistence1 = list.Contains(instance2);            //isExistence1 : false;
Copy after login

The result of this test is false , because they point to different memory addresses, 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 the attributevalues, then it needs to implement the IEquatableinterface!
If you want to continue to see whether objects are equal based on whether the values ​​are equal, please refer to the article: C# Containers, interface classes, 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); 
                }
            }
Copy after login

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
Copy after login

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);
            }
Copy after login

dictCombine merge result is correct, and neither dict1 nor dict2 has changed!

Summary
  Using reference equality brings many benefits, such as References between functions Passing values(by reference). 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)
        {            ...//处理逻辑
        }
    }  
}
Copy after login

Now using the class TestPrivateEncapsulate just written, we first create an instance,

TestPrivateEncapsulate test = new TestPrivateEncapsulate();
Copy after login

 And then call:

List<object> wantedObjs = test.GetRefObjs();
Copy after login

The expected wantedObjs returned should have 3 elements of integer type, 1, 4, 2.

Continue:

List<object> sol = wantedObjs; //我们将sol指向wantedObjssol.Add(5); //加入元素5
Copy after login

When we want to go back and calculate, the original sum of elements of wantedObjs:

test.GetSum();
Copy after login

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;
         }
    }
Copy after login

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 content of .NET Framework-Code example sharing of reference traps. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

How to use char array in C language How to use char array in C language Apr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

See all articles