writing software programs

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

157 recommendations for writing high-quality code to improve C # programs--Recommendation 91: Visible fields should be refactored to properties

implemented. In order for a field to support thread safety, it can only be done by the caller itself.3) The property is supported by the VS compiler, and it also has the ability to implement automatic attributes. The features of automatic attributes are widely used in LINQ, especially in anonymous classes, which can only implement read-only automatic attributes, not fields.4) from a design perspective, the object-oriented perspective, the exposed fields should also use attributes. Changes the s

157 recommendations for writing high-quality code to improve C # programs--Recommendation 111: Avoid bidirectional coupling

(); } class A:isample { private b b; Public void MethodA () { b.methodb (); } } class B { isample A; Public void MethodB () { A.methoda (); } }Interface Isample regulates the behavior of type A, while having type a inherit from Isample. In type B, we program the interface, that is, field A in B is no longer a type, but instead modifies it to the isample type.In general, there should be no b

157 recommendations for writing high-quality code to improve C # programs--Recommendations for exception handling in 85:task

voidTaskscheduler_unobservedtaskexception (Objectsender, Unobservedtaskexceptioneventargs e) { foreach(Exception Iteminche.exception.innerexceptions) {Console.WriteLine ("Exception type: {0}{1} from: {2}{3} exception content: {4}", item. GetType (), Environment.NewLine, item. Source, Environment.NewLine, item. Message); } //identifies the exception as having been observede.setobserved (); } The result of this code run does not output exception information, because there is no gar

157 recommendations for writing high-quality code to improve C # programs--Recommendations for exception handling in 86:parallel

) {Console.WriteLine ("Exception type: {0}{1} from:{2}{3} Exception Content: {4}", item. Innerexception.gettype (),Environment.NewLine, item. Innerexception.source, Environment.NewLine, item. Innerexception.message); }} Console.WriteLine ("The main thread ends immediately"); Console.readkey (); } The output of this piece of code is:Exception type: System.InvalidOperationExceptionFrom: ConsoleApplication2Exception content: Exceptions that occur in parallel tasksThe main thread ends imme

157 recommendations for writing high-quality code to improve C # programs--recommendation 37: Using lambda expressions instead of methods and anonymous methods

; (Delegate(intIintj) {returni +J; }); Actionstring> print=Newactionstring> (Delegate(stringmsg) {Console.WriteLine (msg); });Print (Add (1, 2). ToString ());With anonymous methods, we don't need to declare two methods outside of the main method, so that all code can be written directly in the work method of main, without affecting the clarity of the code. In fact, all of the lines of code that are not more than 3 lines (provided that it is not reused) are recommended to be

157 recommendations for writing high-quality code to improve C # programs--Recommendation 56: More flexibility in controlling the serialization process with the inherited ISerializable interface

want to be deserialized into personanother. The type Personanother is simple, and it doesn't even need to know who will be deserialized into it, and it doesn't need to do any special processing.ISerializable interface This feature is very important, if used properly, in the version upgrade, it can handle the problem of the type because of the changes in the field.Turn from: 157 recommendations for writing high-quality code to improve C #

157 recommendations for writing high-quality code to improve C # programs--Recommendation 79: Use ThreadPool or BackgroundWorker instead of thread

testing of the thread.This recommendation also mentions a type of BackgroundWorker. BackgroundWorker is a technology that uses the thread pool internally, and in WinForm or WPF encoding, it gives the worker and UI threads the ability to interact. If we take a little note, we will find that both thread and threadpool do not provide this interaction capability by default, while BackgroundWorker provides this capability through events. This capability includes reporting progress, supporting comple

157 recommendations for writing high-quality code to improve C # programs--Recommendation 68: Derive exceptions from System.Exception or other common basic exceptions

(message, inner) {_paperinfo=Paperinfo; } protectedPaperencryptexception (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context):Base(info, context) {} Public Override stringMessage {Get { return Base. Message +" "+_paperinfo; } } Public Override voidGetObjectData (SerializationInfo info, StreamingContext context) {info. AddValue ("Args", _paperinfo); Base. GetObjectData (info, context); }

157 recommendations for writing high-quality code to improve C # programs--Recommendation 70: Avoid logging exceptions at lower call stacks

") throw; } }The record exception is also captured at the higher call stack location: Internal void Methodhigh () { try { methodlow (); } Catch (someexception) { logger.write (" exception someexception occurs ") } }This will cause the record to recur. In the case of low call stacks, exceptions are often caught and cannot be processed completely.

157 recommendations for writing high-quality code to improve C # programs--Recommendation 100: Static and instance methods are no different

instance object. We cannot bypass the instance object and invoke the instance method directly from the type itself. So, from a design point of view, if a method is only related to the type itself, then it should be designed as a static method, and if it is related to an instance object of the type, it should be designed as an instance method.Static methods are misunderstood by many people: static methods are naturally synchronous methods. Even programmers with a certain amount of development ex

157 recommendations for writing high-quality code to improve C # programs-Recommendation 49: A protected virtual method should be extracted in Dispose mode

(Nativeresource! =IntPtr.Zero) {Marshal.freehglobal (Nativeresource); Nativeresource=IntPtr.Zero; } //let the type know that they have been releaseddisposed =true; } Public voidSamplepublicmethod () {if(disposed) {Throw NewObjectDisposedException ("SampleClass","SampleClass is disposed"); } //omitted } } classanotherresource:idisposable { Public voidDispose () {}}If you do not provide this protected virtual method for your class, it is likely that you w

157 recommendations for writing high-quality code to improve C # programs--Recommendation 28: Understanding the difference between deferred evaluation and active evaluation

efficiency problem of returning 3 or 2 is not obvious, but putting the application in the Internet system and reducing the amount of traffic in each place will give us a significant performance boost.In fact, the difference between the delay evaluation and the active evaluation should be carefully understood, and the results will be realized in the application: otherwise, there will be some unexpected bugs.Turn from: 157 recommendations for writing h

157 recommendations for writing high-quality code to improve C # programs--Recommendation 101: Using extension methods to "add" methods to existing types

: The extension method must be in a static class, and the class cannot be a nested class; The extension method must be static; The first parameter of an extension method must be the type to be extended, and the This keyword must be added; Extended properties, events are not supported. It is important to note that the extension method can also extend the interface. This makes the interface appear to be extensible as well. This feature of extension methods is widely used

157 recommendations for writing high-quality code to improve C # programs-Recommendation 50: Treat managed and unmanaged resources differently in Dispose mode

resource need to be cleaned manually? You might want to divide the types in C # into two categories, one inheriting the IDisposable interface, and one without inheritance. The former, temporarily known as the non-ordinary type, the latter is called the ordinary type. Non-trivial type because it contains an unmanaged resource, it needs to inherit the IDisposable interface, but this contains the type itself of the unmanaged resource, which is a managed resource. Therefore, a normal type in a mana

157 recommendations for writing high-quality code to improve C # programs--recommendation 12: overriding equals When overriding GetHashCode

two different types based on the string, a slightly improved version of the GetHashCode method is as follows: Public Override int GetHashCode () { return"#" this. Idcode). GetHashCode (); Note that while overriding the Equals method, you should also implement a type-safe interface, iequatable, so the final version of the person type should be as follows: classPerson:iequatable { Public stringIdcode {Get;Private Set; } PublicPerson (stringIdcode) {

157 recommendations for writing high-quality code to improve C # programs--recommendation 10: Consider whether to implement a comparer when creating objects

;Set; } #regionIcomparable Public intCompareTo (Salary other) {returnBasesalary.compareto (Other. Basesalary); } #endregion } classBonuscomparer:icomparer { #regionIcomparer Public intCompare (Salary x, Salary y) {returnX.bonus.compareto (Y.bonus); } #endregion } Static voidMain (string[] args) {ListNewList() { NewSalary () {Name ="Mike", basesalary = the, Bonus = + }, NewSala

157 recommendations for writing high-quality code to improve C # programs--Recommendation 60: Using inner when re-throwing exceptions Exception

); } Catch (SocketException ex) { ex. Data.add ("socketinfo"," network connection failed, please try again later " ); Throw ex; }When capturing at the top, you can get exception information by key values: Catch (SocketException ex) { Console.WriteLine (ex. data["socketinfo"]); }Turn from: 157 recommendations for writing high-qual

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 72: Using semaphores in thread synchronization

heartbeat data to the client at every time. The actual work of the server and the client in the network is two different terminals, but in this example we have simplified it: The worker thread tclient the simulated client, the main thread (UI thread) to emulate the server side. The client detects if the server's heartbeat data is received every 3 seconds, and if there is no heartbeat data, the network connection is disconnected. The code looks like this:AutoResetEvent AutoResetEvent =NewAutoRes

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 74: Beware of thread IsBackground

end immediately.The demo code uses thread, but we should note that threads in the thread pool are the background threads by default.Based on the difference between the front and back threads, you should use the background thread more in the actual encoding. The foreground thread is used only in very critical work, such as when a thread is executing a transaction or some unmanaged resource in possession needs to be freed.Turn from: 157 recommendations for wr

157 recommendations for writing high-quality code to improve C # programs--Recommendation 73: Avoid locking inappropriate synchronization objects

types (such as ArrayList) provided public property syncroot, which allowed us to lock in for some thread-safe operation. So you will feel that we have just concluded that it is not correct. In fact, most of the ArrayList operations do not involve multi-threaded synchronization, so its approach is more of a single-threaded application scenario. Thread synchronization is a very time-consuming (inefficient) operation. If all non-static methods of ArrayList are considered thread-safe, then ArrayLis

Total Pages: 12 1 .... 4 5 6 7 8 .... 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.