C # struct traps in languages

Source: Internet
Author: User
Tags microsoft c

Suppose we want to write a salary management for a university.Program. First, it indicates the employee'sEmployeeClass (employee. CS ):

 01:  Namespace Skyiv. Ben 02: { 03:    Class  Employee04: { 05:      Public String Department { Get ; Private set ;}06:      Public String Name { Get ; Private set ;} 07:      Public decimal Salary { Get ; Set ;} 08:  09:      Public Employee ( String Department, String Name,Decimal Salary) 10: { 11: Department = Department; 12: Name = Name; 13: Salary = salary; 14: } 15:  16:      Public override string Tostring () 17: { 18:       Return string . Format ( "{0} {1} salary: {2: N2 }" , Department, name, salary ); 19: } 20: } 21: }

Next, it indicatesDepartmentClass (department. CS ):

 01:  Namespace Skyiv. Ben 02: { 03:    Class Department04: { 05:      Public String Name { Get ; Private set ;} 06:      Public int Count { Get ; Private set ;} 07:      Public decimal Totalsalary { Get ;Private set ;} 08:  09:      Public Department ( String Name) 10: { 11: Name = Name; 12: } 13:  14:      Public void Add ( Employee Employee)15: { 16: Count ++; 17: Totalsalary + = employee. salary; 18: } 19:  20:      Public override string Tostring () 21: { 22:        Return string . Format ( "{0} Total number of students: {1} total salary: {2: N2 }" , Name, Count, totalsalary ); 23: } 24: } 25: }

Finally, the main program. CS:

 01:  Using System; 02:  Using System. Collections. Generic; 03:  04:  Namespace Skyiv. Ben 05: {06:    Class  Program07: { 08:      Static void Main () 09: { 10:        New  Program (). Run (); 11: } 12:  13:      Void Run () 14: { 15:        VaR Employees = initializeemployees (); 16: Salaryraise (employees ); 17: Statistic (employees ); 18: } 19:  20:      List < Employee > Initializeemployees () 21: { 22:        VaR Employees = New  List < Employee > (); 23: Employees. Add ( New  Employee ( "Principal's office" , "Gao songnian" , 72767.58 m )); 24: Employees. Add ( New  Employee ("Political Department" , "Fang Hongjian" , 31982.45 m )); 25: Employees. Add ( New  Employee ( "Political Department" , "Zhao Xinmei" , 40126.31 m )); 26:        Console . Writeline ( "Sanming university salary schedule :" ); 27: Employees. foreach (E => Console . Writeline (e ));28:        Return Employees; 29: } 30:  31:      Void Salaryraise ( List < Employee > Employees) 32: { 33:        For ( VaR I = 0; I <employees. Count; I ++) employees [I]. Salary + = 10000;34:        Console . Writeline ( Environment . Newline + "After salary increase :" ); 35: Employees. foreach (E => Console . Writeline (e )); 36: } 37:  38:      Void Statistic ( List < Employee > Employees)39: { 40:        VaR Required ments = New  Dictionary < String , Department > (); 41:        Foreach ( VaR Employee In Employees) 42: { 43:         VaR Name = employee. Department; 44:          Department Dep; 45:          If (! Parameters. trygetvalue (name, Out Dep) parameters. Add (name, DEP = New  Department (Name )); 46: Dep. Add (employee ); 47: } 48:        Console . Writeline ( Environment . Newline + "Sanming university salary statistical table :" ); 49:        Foreach ( VaR KVp In Ments) Console . Writeline (kVp. value ); 50: } 51: } 52: }

The running result of this program is as follows:

Three distinct university salary schedule: Principal Office Gao Song annual salary: 72,767.58 Political Department Fang Hongjian salary: 31,982.45 Political Department Zhao Xinmei salary: 40,126.31 after salary increase: Principal Office Gao Song annual salary: 82,767.58 Political Department Fang Hongjian salary: 41,982.45 Zhao Xinmei salary of the Political Department: 50,126.31 Sanming University wage statistical table: number of principals: 1 total salary: 82,767.58 number of political students: 2 total salary: 92,108.76

If we setEmployeeClass (Class) To structure (Struct), The following error will be reported during compilation:

Cs1612: "System. Collections. Generic. List" cannot be modified.

   
    
The return value of. This [int] because it is not a variable.

   

This error occurs in row 33rd of program. CS.Employees [I]. Salary + = 10000;Statement.

I don't understand this cs1612 error. If any of you can explain it, please give it in the comments. Thank you!

 

If we setDepartmentClass (Class) To structure (Struct):

 01:  Namespace Skyiv. Ben 02: { 03:    Struct  Department04: { 05:      Public String Name { Get ; Private set ;}06:      Public int Count { Get ; Private set ;} 07:      Public decimal Totalsalary { Get ; Private set ;} 08:  09:      Public Department ( String Name ): This ()10: { 11: Name = Name; 12: } 13:  14:      Public void Add ( Employee Employee) 15: { 16: Count ++; 17: Totalsalary + = employee. salary; 18: }19:  20:      Public override string Tostring () 21: { 22:        Return string . Format ( "{0} Total number of students: {1} total salary: {2: N2 }" , Name, Count, totalsalary ); 23: } 24: } 25: }

Note that ":This() ", Otherwise Microsoft C # compiler will report an error (but mono C # compiler will not report an error, see: Microsoft C # compiler and mono C # compiler ).

Run the program again. The last three lines of the running result are as follows:

Sanming university salary statistical table: number of principals: 0 total salary: 0.00 number of political students: 0 total salary: 0.00

This is because the currentDepartmentThe structure is a value type, not a reference type. So in the program. CS 46th lineDep. Add (employee );In the statement, the change of the DEP value does not affect the value in the orders. Therefore, the total number of people and total wages are zero.

It is very easy to bypass this trap, in the 46th rowsDep. Add (employee );Add a sentence after the statementParameters [name] = Dep;That's all.

 

In the. NET Framework base class library, there are many structures (Struct). For example:

    • System. int32
    • System. datetime
    • System. Drawing. Size

Be careful when using it.

In addition, note that methods such as ADD and adddays of datetime do not change the value of datetime. Instead, return a new datetime, whose value is the result of this operation. Therefore, the following statement is invalid:

 
For(VaRDate =Datetime. Minvalue; date <Datetime. Today; date. adddays (1 ))

Which of the following statements is true:

 
For(VaRDate =Datetime. Minvalue; date <Datetime. Today; Date = date. adddays (1 ))

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.