Chapter 8th of. NET Design Specifications: usage specifications,. net Design Specifications

Source: Internet
Author: User

Chapter 8th of. NET Design Specifications: usage specifications,. net Design Specifications
Chapter 4: Use a standard 8th Array

Set should be used preferentially in public APIs to avoid using arrays.

Do not use read-only array fields. Although fields are read-only, you cannot modify them, but you can modify the elements in the array.

Consider using irregular arrays instead of multi-dimensional arrays.

  

8.2 modify attributes

Add the suffix "Attribute" when naming custom property classes.

You must use AttributeUsageAttribute to define your own modifier attributes.

To define a required parameter as a read-only attribute.

You must provide constructors to initialize required parameters. The name of each parameter should be the same as the name of the corresponding attribute (but the case is different ).

Avoid providing constructors to initialize optional attributes (optional parameters.

Avoid overloading constructors with custom modifier attributes.

Try to seal up the custom property classes. This will make the search for modified attributes faster.

  

8.3 set

Do not use weak types in public APIs.

Do not use ArrayList or List <T> in public APIs.

Do not use Hashtable or Dictionary <TKey, TValue> in public APIs.

Do not use IEnumerator <T> or IEnumerator or any other type that implements either of these interfaces, unless it is the return type of the GetEnumerator method.

Do not implement both IEnumerator <T> and IEnumerable <T> In the same type. This is also true for non-generic interfaces IEnumerator and Enumerable.

Use the most generic type as the parameter type. Most members with set parameters use the IEnumerable <T> interface.

Avoid using ICollection <T> or ICollection as parameters-if the purpose is only to access the Count attribute of this interface.

Do not provide configurable set attributes.

Use Collection <T> or its subclass-if the property or return value represents a set that can be read and written.

Use ReadOnlyCollection <T> or its subclass. In rare cases, use IEnumerable <T>. If the attribute or return value represents a read-only set.

Consider using a subclass of a generic set base class instead of using the set directly.

Consider using Collection <T> or ReadOnlyCollection <T> as the return values of common methods and common attributes.

Consider using a key set-if the elements stored in the set have unique key values (names, IDs, etc ). A key set is a set that can be accessed by both integer and key value indexes. It is usually derived from KeyedCollection <TKey, TItem> during implementation.

Do not return null from the set attribute or the method that returns a set value. Return an empty set or an empty array.

Do not let the property return the snapshot set. The property should return the live set.

Use a snapshot set or a live IEnumerable <T> (or its subclass) to represent an unstable set (that is, a set that may change without explicit modification ).

Do not let the property return the snapshot set. The property should return the live set.

Use a snapshot set or a live IEnumerable <T> (or its subclass) to represent an unstable set (that is, a set that may change without explicit modification ).

Implement IEnumerable <T> when designing a new set. If appropriate, you can also consider implementing ICollection <T> or even IList <T>.

Consider implementing non-generic set interfaces (IList and ICollection)-If you often need to pass the set to the API whose parameters are input.

Avoid implementing the set interface for the type-if the type API is complex and has nothing to do with the concept of the set.

Do not inherit from non-generic set base classes, such as CollectionBase. Use Collection <T>, ReadOnlyCollection <T>, and KeyedCollection <TKey, TItem>.

Add the suffix "Dictionary" when naming a type-if the type implements the IDictionary or IDictionary <TKey, TValue> interface.

Add the "Collection" suffix when naming a type-if the type implements the IEnumerable (or any of its subclasses) interface, the type represents a list of elements.

Use a proper data structure name when naming a custom data structure.

Avoid adding a suffix that represents the specific implementation of a set during abstract naming, for example, "Collections list" or "Hashtable ".

Consider using the type name of the Set element as the prefix of the Set Name.

Consider adding the "ReadOnly" prefix to the name of the read-only set. In the future, it is possible to add the corresponding writable set or the corresponding writable set already exists in the framework.

 

8.4 DateTime and DateTimeOffset

Use DateTimeOffset-if you want to represent an exact time point. For example, it is used to calculate the current time, the start time of the transaction, the time when the file was modified, and the time when the event was recorded. If you do not know the time zone, use UTC. Compared with DateTime, the preceding scenario is more common, so DateTimeOffset should be used by default.

DateTime should be used in any situations where absolute time points are not suitable, such as the time when the store opens doors in different time zones.

Use DateTime if you do not know the time zone or sometimes do not know the time zone. This may happen if the data comes from an older system.

Do not use DateTimeKind when DateTimeOffset can be used.

DateTime is used to represent all dates (such as birthdays), and the time part is set to 00:00:00. Do not use DateTimeOffset to represent dates.

 

8.5 ICloneable

Do not implement ICloneable.

Do not use ICloneable in public APIs.

Consider defining the Clone method for the type that requires the Clone mechanism. It must be clearly stated in the document that the method is executed for deep replication or light replication.

  

8.6 IComparable <T> and IEquatable <T>

To implement IEquatable for the value type <T>.

When implementing IEquatable <T>. Equals, the rules set to overwrite Object. Equals must also be followed.

You must overwrite Object. Equals while implementing IEquatable <T>.

Consider overloading operator = and operator while implementing IEquatable <T>! =.

You must implement IEquatable while implementing IComparable <T>.

Consider overloading the comparison operators (<,>, <=,> =) while implementing IComparable <T> ).

 

8.7 IDisposable

 

8.8 Nullable <T>

Consider using Nullable <T> to indicate values that may not exist (such as optional values ). For example, if you want to return a strongly typed record from the database, and one of the attributes corresponds to a dispensable column in the table, you should use Nullable <T>.

Do not use Nullable <T>-unless in a similar case, you may consider replacing it with a reference type because the reference type can be null. For example, null cannot be used to represent optional parameters.

Avoid using Nullable <bool> to indicate general values with three states. Nullable <bool> should be used only to indicate true, false, and unavailable boolean values. If you want to at least indicate values in three States (for example, yes, no, and cancel), you can use enumeration.

Avoid using System. DBNull. Use Nullable <T> first.

 

8.9 Object

To override the Object. Equals method, follow the contract it defines.

The GetHashCode method must be overwritten when the Equaals method is overwritten.

Consider implementing the IEquatable <T> interface while overwriting the Object. Equals method.

Do not throw an exception from the Equals method.

The Equals method of the value type to be overwritten.

You need to implement IEquatable <T> to provide an Equals overload method with the value type itself as the parameter.

Consider overwriting Equals to provide equal value semantics-if the reference type represents a value. For example, for reference types that represent numeric values or other mathematical questions, you can consider overwriting the Equals method.

Do not implement equivalent semantics for variable reference types.

Override the GetHashCode method-if the Object. Equals method is overwritten.

Make sure that if the Object. Equals method returns true for any two objects, the GetHashCode method returns the same value.

Do everything you can to make the GetHashCode method of the type generate hash codes with random distribution.

Make sure that the GetHashCode returns the same value no matter how you change the object.

Avoid throwing an exception from the GetHashCode method.

Overwrite the ToString method-returns a string that is both useful and easy to read.

Try to make the ToString () method return a short string.

Returns a unique string for each instance.

You must use a name that is easy to read, rather than an ID that is unique but incomprehensible.

To return information related to the culture, format the string based on the culture of the current thread.

You need to provide the reload method ToString (string format) or implement the IFormattable interface-if the string returned by the ToString () method is related to the culture, or there are multiple methods to format the string. For example, DateTime provides both the overload method and the IFormattable interface.

Do not return an empty string or null from the ToString () method.

Avoid throwing an exception from the ToString () method.

Make sure that the ToString () method does not produce any side effects.

To report security-related information through the ToString () override method, you must first obtain the relevant license. If you cannot obtain a license, you should remove security-related information from the returned string.

We recommend that the string output by the ToString method be correctly parsed for this type of parsing method.

  

8.10 serialization

Serialization should be taken into account when designing the experience type.

Consider letting types support data protocol serialization-if you need to use this type in Web Services, or you need to make the type persistent in Web Services.

Consider making types only support XML serialization, or support both data protocol serialization and XML Xu Lihua-if you need more control over the XML format generated during the Xu Lihua type.

Support runtime serialization for types-if you need to transfer types across the. NET Remoting boundary.

Do not support XML serialization or runtime serialization only for general persistence purposes. Data Protocol serialization should be prioritized.

Consider defining members of the type as public-if the type is used in an environment that is not completely trusted.

Getter and setter must be applied to all attributes of DataMemberAttribute. To enable the data protocol serialization program to serialize data types, the attributes must include getter and setter. If the type is not used in an environment that is not completely trusted, one or two of getter and setter may not be public.

The deserialization destroy function is used to initialize the anti-sequence instance.

Consider using KnownTypeAttribute to represent the specific types that should be used in deserialization of complex object graphs.

Backward compatibility and forward compatibility should be considered when a serializable type is created or changed.

IExtensibleDataObject is implemented to support bidirectional conversion between old and new versions.

Avoid taking XML serialization into special consideration when designing types, unless there is a strong reason to control the generated XML content. The XML serialization technology has been replaced by the previous data protocol serialization technology.

Consider implementing the IXmlSerializable interface-if the XML content generated after the XML serialization attribute is applied cannot meet the requirements. This interface has two methods: ReadXml and WriteXml, which can be used to completely control the generated XML content. You can also apply XmlSchemaProviderAttribute to the type to control the generated XML architecture.

Support runtime serialization-if the type is used for NET Remoting. For example, because the System. AddIn namespace uses. NET Remoting, all types of data transmitted between System. AddIn's add-in must support runtime serialization.

Consider implementing the runtime serialization mode-if you want to fully control the entire serialization process. For example, you want to convert data during serialization or deserialization.

To define a serialized constructor as protected and provide two parameters, the parameter type and name must be identical to the following sample code.

The member that needs to explicitly implement the ISerializable interface.

A connection requirement must be provided to the Iserializable. GetObjectData implementation application to ensure that only the fully trusted code and runtime serialization program can access this member.

 

8.11 Uri

Use System. Uri to represent URI and URL data.

Consider providing string-based reload members for the most common members with the System. Uri parameter.

Indecent without thinking about all the members based on System. Uri to provide string-based overload members.

You need to call an overload member based on System. Uri-if any.

Do not store URI/URL data in strings.

  

8.12 Use of System. Xml

Do not use XmlNode or XmlDocument to represent XML data. Use IXPathNavigable, XmlReader, XmlWriter, or XNode as much as possible. XmlNode and XmlDocument are not designed to expose external APIs.

To use XmlReader, IXPathNavigable, or XNode as the input or output type in a member that accepts or returns XML.

Do not derive subclass from XmlDocument-if you want to create a type that represents the XML view of the lower-level object model or data source.

  

8.13 equality Operators

Do not overload only one of the Equality operators.

Make sure that Object. Equals and equality operators have identical semantics and similar performance.

Avoid throwing exceptions from equality operators.

The equality operator of the value type to be reloaded-if equality is meaningful.

Avoid overloading equality operators of variable reference types.

Avoid overloading the equality operators that reference the type-if implemented, the implementation of equality is much slower.

  

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.