Do C # properties always have backstage backup fields?

I know that when we use properties in C #, the compiler always generates methods for getting and setting them in CIL for them (for example, get_PropertyName and set_PropertyName), for example, consider the following code fragment:

    class Program
    {
        class Test
        {
            public string Name { get; set; }
        }
        static void Main(string[] args)
        {
            //Here I'm using reflection to inspect methods of Test class
            Type type = typeof(Test);
            foreach (var item in type.GetMethods())
            {
                Console.WriteLine(item.Name);
            }
        }
    } 

This program will produce the output with the help of methods Test, among which are get_Name, and set_Name- getters and setters, of which I spoke. As far as I understand, if getters and setters are created behind the scenes, then an auxiliary field should also be created from which / in which getters and setters get / set values. So, from the previous example, I can use reflection to check the fields of the Test class, for example:

    static void Main(string[] args)
    {
        Type type = typeof(Test);
        foreach (var item in type.GetFields())
        {
            Console.WriteLine(item.Name);
        }
    } 

, , , private , . , , , , ( get; set;)?

+6
2

, :

{get;set;}

{get;}

, ; BindingFlags.NonPublic | BindingFlags.Instance GetFields(), :

foreach (var item in type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
    Console.WriteLine(item.Name);
}

unpronouncable name <> - <Name>k__BackingField , : ( .. , ).

: , ; :

public int Value => 42; // no field

public int Name { get { return obj.Name; } set { obj.Name = value; } }
+13

, , , ( get set;?

,

public int ReadWriteProperty { get; set; }
public int ReadOnlyProperty { get; }

, . /, :

public int Zero => 0;

public int IgnoresSetter
{
    get { return 10; }
    set { /* Meh. Whatever you say, I'm still going to return 10 in the getter... */ }
}

.

+13

Source: https://habr.com/ru/post/1016161/


All Articles