2 small issues of struct in C #

Source: Internet
Author: User

1. Set the linked list. The common code is as follows:
Public struct Links
{
Public int data;
Public Links next;
}
The preceding code compilation error occurs: "Links. next", a structure member of the "Links" type, leads to loops in the structure layout.

There are two solutions:
A. You can use the class instead of struct.
B. Stick to struct, so you need to compromise and add an object member and the Links attribute to save the nation. The Code is as follows:
Public struct Links
{
Public int data;
Private object _ next;
Public Links next
{
Get {return (Links) _ next ;}
Set {_ next = value ;}
}
}
 

2. assign values to the struct members of the struct array or class. Example code:
List <Links> arr = new List <Links> ();
Arr. Add (new Links ());
Arr [0]. data = 123;
The above code has an error during compilation: the return value of "System. Collections. Generic. List <Links>. this [int]" cannot be modified because it is not a variable.
The cause of the error is that struct is a value type. First, arr [0] returns a Links, and only returns a copy. It is not a reference to the position 0 in the arr array,
Directly modifying the data attribute of a copy does not make any sense, because after the modification, the copy is discarded.
To prevent developers from making this mistake, Microsoft defines it as a compilation error. If you want to modify the data attribute of the 0th elements in the array, change the code:
List <Links> arr = new List <Links> ();
Arr. Add (new Links ());

Links tmp = arr [0];
Tmp. data = 123;
Arr [0]. data = tmp;
The above step is to directly replace the 0th elements, and the old data is waiting for recovery.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.