Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Field, attribute, read-only, Constructor assignment and reflection assignment in C #

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about the sample analysis of fields, properties, read-only, constructor assignments, and reflection assignments in C #. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The question of field, property, and constructor assignment in C # is as follows:

First of all, a few questions are raised:

1. How to implement your own injection framework?

2. What is the difference between fields and automatic properties?

3. What is the difference between direct assignment and constructor assignment in field and automatic property declaration?

4. Why can both read-only fields and read-only automatic properties (only get without a set accessor) be assigned in the constructor?

5. Can reflection assign values to read-only fields or read-only properties?

6. What is the difference between automatic attributes and ordinary attributes?

These are the problems I encountered when trying to write my own injection implementation. These questions should have been learned in the first lesson of learning C#. I think someone on the Internet shared that during the interview, he was asked by the interviewer why read-only fields and read-only automatic properties could be assigned in the constructor, but he did not answer them. Then he wrote an article to discuss this question, but did not get an obvious answer, it is a pity. There are some ReadOnly features about read-only properties on the Internet. Just skip these articles. It's not helpful to read the old version of C# now.

Give the answer.

2. Attributes have more get/set accessors than fields; a field is a memory space declared in memory, which can actually store values; attributes are used like fields, but they can have their own code snippets and can be assigned values, because to access attributes is to call the get/set method of the property to assign values to the field (or not to manipulate the field). On MSDN, it is recommended that fields are decorated with private/protected as private variables of the class, while attributes are often decorated with public as common attributes; fields are read and operated directly on memory, and properties are called get/set accessors, so fields are faster than properties.

3. To be exact, there is no difference. The only difference is that the direct assignment is executed first, and the constructor assignment is executed later. In the generated IL intermediate language (the C # code is compiled into IL code and then into assembly language), the field direct assignment and the constructor assignment are in the same code segment (constructor).

4. This question can be answered in conjunction with the above questions. The constructor is the first to be accessed as an entry to instantiate a class. The direct assignment of the field is actually performed in the constructor, so there is no difference between the direct assignment and the constructor assignment. " The limit of "read-only" is only maintained by the C # compiler (CLR). I think the full name should be called "read-only except constructor". This is the rule of C # syntax. (of course, direct assignment is actually placed in the constructor for assignment. If the constructor cannot be assigned, the read-only field has no value and no declaration.)

5. This question can be answered together with the above question. You can assign values to self-reading fields through reflection, but you cannot assign values to read-only properties (you can try if you don't believe it). The assignment to the read-only field is due to bypassing the read-only display of the C # compiler (CLR). If the read-only attribute is assigned, the set accessor is still called to assign the field, because there is no set accessor, so an error will be reported after it is allowed. So the question is, why can read-only automatic properties be assigned in a constructor without a set accessor? In fact, read-only automatic properties are assigned in the constructor, essentially assigning values to fields, which have nothing to do with the get/set accessor of the property.

6. What's the difference? Automatic attributes have been emphasized above because they are different from normal properties, such as read-only ordinary properties (without set accessors) that cannot be assigned in the constructor. Before there are no automatic properties, the normal property usage step is to first declare a field such as _ id, then declare a property Id, and do some operations in the get and set accessors, most of which are operations on the field _ id, but sometimes have nothing to do with the field. Ordinary properties can pass through "." like fields. But have code snippets like methods (normal properties never open up memory space).

However, automatic attributes have been introduced since Cure 3.0, such as public int id {get; set;}, and public string FirstName {get; set;} = "Jane" has been introduced since Cure 6.0. Automatic attributes must open up memory space before there is a direct assignment of automatic attributes. In fact, declaring automatic properties in a class declares a hidden field in a compiled IL intermediate language, then generates a get/set method for the hidden field, and then generates a get/set accessor. This explains why read-only normal properties cannot be assigned (and directly assigned) in the constructor, while read-only automatic properties can be assigned (and directly assigned) in the constructor, because the constructor in the generated IL code operates on hidden fields and does not have a set accessor that accesses the property, whether directly or directly. (note that only the automatic properties in the class are mentioned here, and there can also be automatic properties in the interface, but the automatic properties of the interface do not generate hidden fields and just define the get/set accessor.)

Start to explain.

The IL intermediate language code generated by C # can be known more clearly.

Public class User {public int id = 0; public int age {get; set;} = 1; public User () {id = 2; age = 3;}}

As you can see, the automatic property generates a get/set method + property code snippet that hides the private field + private field with the name 'kryptonBackingField.'

You can see that the IL code generates the User constructor .ctor, and ctor is the constructor (Constructor).

Both direct assignment and constructor assignment are performed in .ctor, and the operation is on the field, and the assignment of the automatic property is on the hidden field.

Public interface IUser {int id {get; set;}}

As you can see, the automatic properties in the interface do not generate hidden fields.

Other instructions

1. As mentioned above, "reflection can assign values to read-only fields, but not to read-only properties." Cannot assign a value to a read-only property because there is no set accessor. But we already know that we can assign values to fields, and read-only properties generate hidden fields, so can we indirectly assign values to automatic properties by assigning values to hidden fields? The answer is yes!

Define read-only automatic properties of User

Public class User {public int age {get;} = 1; public User () {age = 3;}}

Reflection assignment code for the console:

Var user = new User (); try {typeof (User) .GetProperty ("age") .SetValue (user,9);} catch {Console.WriteLine ("read-only property assignment failed");} typeof (User) .GetField ("k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic) .SetValue (user,9); Console.WriteLine (user.age); Console.Read ()

Running

2. Because hidden fields are private, BindingFlags.NonPublic is required to get hidden fields.

3. The read-only automatic property indicates that you don't want to be accessed, so why assign a value to it? This question. Just for fun, I don't think there is any chance to use it in the project.

Thank you for reading! This is the end of this article on "sample analysis of field, attribute, read-only, constructor assignment and reflection assignment in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report