writing software programs

Alibabacloud.com offers a wide variety of articles about writing software programs, easily find your writing software programs information here online.

"Go" writing high-quality Code 157 recommendations for improving C # programs--recommendation 36: Using delegate declarations in the FCL

Delegate void Eventhandlerobject sender, Teventargs e);Represents a delegate declaration for a thread method: Public Delegate void ThreadStart (); Public Delegate void Parameterizedthreadstart (object obj);Delegate declaration that represents the asynchronous callback:Public Delegate void AsyncCallback (IAsyncResult ar);Each type of delegate declaration in the FCL represents a special kind of use, although it can be replaced with its own delegate declaration, but it is not necessary to do so,

"Go" writing high-quality Code 157 recommendations for improving C # programs--recommendation 107: Distinguishing between static classes and singleton

Recommendation 107: Distinguish between static classes and single casesThere is a view that static classes can be used as a way to implement a single-piece mode. In fact, this is not appropriate. From a traditional standpoint, a singleton is an instance object. Static classes do not meet this point. Static classes also directly violate the two object-oriented three characteristics: inheritance and polymorphism.An instance of a static class that cannot inherit from another type is as follows:

"Go" writing high-quality Code 157 recommendations for improving C # programs--recommendation 96: Members should prioritize exposing base types or interfaces

Recommendation 96: Members should prioritize exposing base types or interfacesType members will allow the type to support more applications if the public and the type or interface are given precedence.The most typical example in the FCL is the functional operation of the collection. The set is divided into several types according to function, such as listMicrosoft implemented such a static type enumerable in the FCL, which has a static method: Public Static Ienumerable() { return emptyenumer

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 156: Using features to provide multiple versions of an application

("Standalone feature edition"); } } classProgram {Static voidMain (string[] args) {MyService service=NewMyService (); Service. Testing (); Service. Getinfofromnet (); } }To implement two different functions, you need to define the file at the beginning of the program entry:#define ONLINE#define OFFLINEThis compilation symbol must be at the very beginning of the file. At the same time, the definition is valid only for this document. If you want to define a global compi

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 99: Overriding should not use sub-class parameters

Recommendation 99: Overriding should not use child class parametersWhen overridden, if a child class parameter is used, it may deviate from the designer's intended target. For example, there is an inheritance system as follows: class Employee { } class manager:employee { }The Setsalary method in type Managersalary now overrides the same method in salary, and the overridden method takes a subclass parameter: class Salary { publicvoid setsalary (Employee e)

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 149: Using table-driven methods to avoid too long if and switch branches

"); } Public voidShopping () {Console.WriteLine ("Shopping"); } Public voidTemp () {Console.WriteLine ("Temporary Arrangements"); } }Table-driven method is a kind of design idea, also can be called pattern. In the actual coding, it should not be confined to the index to drive the behavior, but should be applied flexibly according to the actual situation.Turn from: 157 recommendations for writing high-quality code to improve C #

"Go" writing high-quality Code 157 recommendations for improving C # programs--recommendation 45: Specifying contravariance for generic type parameters

Recommendation 45: Specifying contravariance for generic type parametersContravariance refers to a method's parameters can be a base class for a delegate or a generic interface's parameter type. Common delegates that support contravariance in FCL4.0 are:FuncPredicateCommon delegates are:IcomparerThe following example shows the benefits of specifying the inverse of a generic type parameter: classProgram {Static voidMain () {Programmer P=NewProgrammer {Name ="Mike" }; Manager m=NewManager {Name

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 19: Class with more efficient objects and collections.

collection initialization setting, the compiler calls the Add method on the collection after the collection object has been created.The above code demonstrates how to create a new object or an existing object in an initialization statement, as well as a null value.However, initializing the settings is not only convenient for object and collection initialization, the properties of the anonymous type in the collection returned by the LINQ query are read-only, and if you need to assign a value to

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 8: Avoid providing explicit values to elements of enumerated types

Note that there are exceptions to this recommendation. For example, when you specify the System.FlagsAttribute property for an enumeration type, it means that you can perform bitwise operations on and, or, not, and XOR on these values, so that the value of each element of the enumeration is required to be a number of powers of 2, and the exponent is incremented sequentially. For example, the week version should be:[Flags]enumWeek {None=0x0, Monday=0x1, Tuesday=0x2, Wednesday=0x4, Thursday=

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 90: Do not provide a public construction method for abstract classes

Recommendation 90: Do not provide a public construction method for abstract classesFirst, an abstract class can have a construction method. Even if you do not specify a constructor method for an abstract class, the compiler will generate a default protected constructor for us. The following is a standard simplest abstract class: Abstract class Myabstractclass { protected Myabstractclass () {} }Second, the methods of abstract classes should not be public or internal. Abstract cla

"Go" writing high-quality Code 157 recommendations for improving C # programs--recommendation 64: Adding Tester-doer mode to loops instead of placing try-catch inside loops

Recommendation 64: Increase the tester-doer mode for loops instead of placing the try-catch inside the loopIf you need to throw an exception in a loop, you need to be particularly careful that throwing an exception is a fairly performance-impacting process. You should try to judge some of the conditions of the anomaly in the loop and then process it according to the conditions.Do a test:Stopwatch Watch =stopwatch.startnew (); intx =0; for(inti =0; I 10000; i++) { Try

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 55: Reduce serializable fields with custom features

{//serializing a type to a string Public Static stringSerialize(T t) {using(MemoryStream stream =NewMemoryStream ()) {BinaryFormatter Formatter=NewBinaryFormatter (); Formatter. Serialize (stream, T); returnSystem.Text.Encoding.UTF8.GetString (stream. ToArray ()); } } //serializing a type to a file Public Static voidSerializetofilestringPathstringfullName) { if(!directory.exists (path)) {directory.createdirectory (pat

157 recommendations for writing high-quality code to improve C # programs--Recommendation 75: Beware of threads not starting immediately

synchronous code:Static int_id =0; Static voidMain () { for(inti =0; I Ten; i++, _id++) {NewMethod1 (I, _id); } console.readline (); } Private Static voidNEWMETHOD1 (intIintRealtimeid) {Thread T=NewThread (() ={Console.WriteLine (string. Format ("{0}:{1}", Thread.CurrentThread.Name, Realtimeid)); }); T.name=string. Format ("thread{0}", i); T.isbackground=true; T.start (); } } The above code output:thread0:0Thread3:3Thread1:1Thread2:2Thread5:5Thread4:4Thread6:6Thread7:7

157 recommendations for writing high-quality code to improve C # programs--Recommendation 77: correctly stopping threads

an external cancel signal, and exiting if there is such a signal. As you can see, the thread itself actually plays a major role in the mechanism of properly stopping threads. The work code in the example is simple but sufficient to illustrate the problem. More complex computational work should also be done in such a way as to properly and correctly handle the exit.The key type in collaborative cancellation is CancellationTokenSource. It has a key property Token,token is a value type named Cance

157 recommendations for writing high-quality code to improve C # programs--Recommendation 5: Use int to ensure that value types can also be null

look at the reciprocal conversions of nullable types and primitive types. The primitive type provides an implicit conversion of its corresponding nullable type, as follows: int NULL ; int 0 ; In turn, nullable types are not implicitly convertible to the corresponding primitive type, and the correct conversion form is as follows: int 123 ; int J; if (I.hasvalue) { = i.value; } Else { 0; But does this code look a bit cumber

157 recommendations for writing high-quality code to improve C # programs--Recommendation 2: Using the default transformation method

the toboolean above, and if this type of transformation is not supported, a InvalidCastException should be thrown instead of a notimplementedexception.System.bitconverter provides a way to convert between primitive types and byte arrays, which is not discussed here.4. Using CLR-supported transformationsThe transformation that the CLR supports, that is, upstream and downstream transformation. This concept is first proposed in Java, which is actually the conversion between the base class and the

157 recommendations for writing high-quality code to improve C # programs--Recommendation 44: Understanding covariance in delegates

: getemployeehanlder Getamanager; GetemployeehanlderTo get the above code to compile, you also need to specify the OUT keyword for the generic parameter in the delegate: Public Delegate T getemployeehanlder out t> (string name);Unless the delegate declaration is certainly not used for variability, specifying the OUT keyword for a generic parameter in a delegate expands the application of the delegate and is recommended to be used forever in the actual encoding process. In f

157 recommendations for writing high-quality code to improve C # programs--Recommendation 40: Use the event keyword to enforce protection for delegates

delegate chain to null:null;2) fileuploaded can be called externally, such as:F1. Fileuploaded (ten);This should not be allowed, because when the caller is notified, it should be the Fileuploader class's own responsibility, rather than the caller itself to decide. The event keyword is raised in this case, and it is protected by the delegate.Will Public Fileuploadedhandler fileuploaded;Switch Public Event Fileuploadedhandler fileuploaded;In this way, several of the above mentioned situations are

157 recommendations for writing high-quality code to improve C # programs--recommendation 17: Loop traversal with foreach in most cases

instance void[mscorlib]system.idisposable::D ispose ()il_0034: NOP il_0035: endfinally } //End Handler il_0036: NOP il_0037: Pager Int32[Mscorlib]system.console::read ()il_003c: Pop il_003d: ret} //end of Method Program::mainViewing the IL code shows that the get_current () and MoveNext () methods are still called by the runtime.After the MoveNext () method is called, if the result is true, jump to the beginning of the loop. In fact, the Foreach loop and the while loop are

157 recommendations for writing high-quality code to improve C # programs--Recommendation 38: Beware of traps in closures

with the following code: Static voidMain (string[] args) {ListNewList(); for(inti =0; I 5; i++) {Tempclass Tempclass=NewTempclass (); Tempclass.i=i; Action T=Tempclass.tempfuc; Lists. ADD (t); } foreach(Action tinchlists) {T (); } } classTempclass { Public inti; Public voidTempfuc () {Console.WriteLine (i.ToString ()); } }Turn from: 157 recommendations for writing high-quality code to imp

Total Pages: 12 1 .... 3 4 5 6 7 .... 12 Go to: Go

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.