Recommended Reading | between attributes and data members can directly access should be how to choose

EDITORIAL

When writing C # code if you have had this experience: often mixed property and public data members. After all, they are basically the same usage, for the use of it seems to be no difference ah. In fact, public data members of my class is also often used to define constants for the sake of simplicity, some just need the external exposure (defined as the use of some global constants) class constants, are also achieved by defining public data members . World-renowned experts in the world to see until Bill Wagnerlater that this "More Effective C #" should try to realize that "the use of property data members instead of directly accessible." Because the property has modified convenience, multi-threaded support, and so on.

Author: according to Le Wish
Original Address: https://www.cnblogs.com/yilezhu/p/11221447.html

Why should make full use of property

Property has been featured C # language, the current attribute mechanism than C # just when it introduced more complete, which allows developers to perform various functions properties, for example, you can give getterand setterset different access rights. Compared with the data members directly to programmatically, automatic properties can save a lot of programming work, and developers can easily define the read-only attribute through this mechanism. In addition to the expression may also be combined as a main component (expression-bodied) writing the code becomes more compact. We should not continue to create public (publish) field types With these mechanisms, should not continue to write by hand getand setmethods. Properties can either make the caller through a public interface to access related data members, but also to ensure that members get an object-oriented package.

Note: In C # language, attributes such as data elements can be accessed as members, but they are actually implemented by the method.

Easy to modify

In all classes and structures, it should be more use of property, which would allow you when it finds new requirements, more convenient to modify the code. For example, if you now decide Customerthe type of name(名字)data should not appear blank, then only you need to modify the Namecode to property:

public class Customer
{
    private string name;
    public string name
    {
        get=>name;
        set
        {
            if(string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentException(
                    "Name connot be blank",
                    nameof(Name)
                );
            }
            name=value;
        }
    }
}

If we had not implemented by the public property Name, instead of using public data members, so now we must find the library set up through each line of code in the member's code and modify one by one, it will waste a lot of time.

Multi-threading support

Because properties are achieved by a method, so developers can easily add it to support multi-threading. For example, can be achieved as follows getand · setaccessor, the outside world Nameaccess to data are synchronized:

public class Customer
{
    private object syncHandle = new object();

    private string name;
    public string name
    {
        get
        {
            lock (syncHandle)
            {
                return name;
            }
        }
        set
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentException(
                    "Name connot be blank",
                    nameof(Name)
                );
            }

            lock (syncHandle)
            {
                name = value;
            }
        }
    }
}

The method has the advantage, there is the whole property

Some of the features of C # methods may have also reflected in the property upon which it is clear that a property can also be declared as virtual:

public class Customer
{
    public virtual string Name
    {
        get;
        set;
    }
}

Note: just a few examples involving local attributes are used in implicit writing. When using implicit written, developers do not own the property getterand setterin the preparation of too much logic. In other words, we are represented in the field by relatively simple attributes, this property through without having to build a large number of template code, the compiler automatically creates a private field (the field is often referred to as back-up field, and for us to achieve get, setboth simple logic required to access the device).

It can be abstract, and become part of the interface

Attribute may be abstract, thus becoming part of the interface definition, this attribute of Hermit to write similar properties. The following code, it demonstrates how to define attributes in a generic interface. Although the wording Hermit similar properties, but this property was not achieved corresponding to the definition of the interface is only required to achieve the properties of this interface type must meet contract entered into the interface, which is necessary to provide the correct Nameand Valuethese two properties :

public interface INameValuePair<T>
{
    string Name { get; }
    T Value { get; set; }
}

Easily control access to and set permissions

For the type of property, its accessor into getter(获取器)the setter(设置器)two separate methods, which makes us different modifiers can be applied to both, so as to control the external obtain permissions and set permissions for the property. Since these two rights can be adjusted separately, so that we can attribute a more flexible by encapsulating data elements:

public class Customer
{
    public virtual string Name
    {
        get;
        protected set;
    }
}

With attribute parameters

Property not only for simple numeric field. If you want to publish certain types of content that can be accessed using the index in its interface, you can create an indexer. This is equivalent properties with parameters, or the parameters of the property. The following such an approach is useful, use it to create a property to return an element in the sequence:

public class Customer
{
    public virtual string Name
    {
        get;
        protected set;
    }

    public int this[int index]
    {
        get => theValues[index];
        set => theValues[index] = value;
    }

    private int[] theValues = new int[100];
}
//Accessing an indexer;
int val=someCustomer[i];

Further, if the parameter is an integer of one-dimensional index is, the data may be involved in binding, if the parameter is not an integer is a dimensional index, may be used to define mapping relationships:

private Dictionary<string, Address> addressValues;
    public Address this[string name]
    {
        get => addressValues[name];
        set => addressValues[name] = value;
    }

Note: The index is always to use this keyword to declare. Because C # does not allow to the index is a name, it must differ in the parameter list the same type of index, otherwise it will be ambiguous.
In addition, the index must clearly realize it, but not as the default generated by the system as simple properties.

other instructions

Then late into property data members

Although the property is a very good mechanism, but there are people who want to create a common data members, and then under indeed necessary and then replace it with property to use the property have the advantage. This idea sounds very reasonable, but does not actually appropriate. For example, the following data members define a common code:

public class Customer
{
    public string Name;
}
string name = customerOne.Name;
customerOne.Name = "yilezhu";

In fact, I have often used this way, but are defined some static global constant.
Although the use of the property that can be accessed as data members, but from the point of view of MSIL, is not the case, because the instruction and access data members used to access the property used is different. So if the data member into a property, it will undermine the binary level compatibility mechanism, making it difficult to independently update a particular assembly, to be completely updated.

Loss in performance properties

You may want to ask, in the form of property to access the data faster, faster still access the data in the form of a member of? In fact, although the former does not exceed the efficiency of the latter, but not necessarily behind it. Because the JIT compiler would inline method calls certain process, which also includes an attribute. If the compiler inline processing of attributes, then its efficiency will be the same as the data members. Even without inline, the difference may be negligible.

to sum up

Today to introduce the use of property to access the data members many advantages, it is recommended that if you want to publish data on the type of public or protected interface, then it should be released in the form of property for the sequence or the dictionary, it should be indexer form of release. While in the daily development in the form of property to encapsulate variable will take one to two minutes of your time, but if you do not start using the property, then I wanted to design a property, you may have to use several hours to fix the . Now spend more time in the future will save a lot of effort.
Most of the article content from watching "More Effective C #" notes the contents of the first bar made, of course I will follow-up the remaining 50 upgrade method C # code to summarize the recording, please look forward to it. If you are interested you can add DotNetCore real items 637 326 624 exchange group to communicate with everyone.

Guess you like

Origin www.cnblogs.com/yilezhu/p/11221447.html