the friendly information.Situation ThreeIf the underlying exception does not make sense in the context of a high-level operation, consider capturing these underlying exceptions and throwing new meaningful exceptions. If a invalidcastexception is raised as a new ArgumentException.A typical example of a properly thrown exception is capturing the underlying API error code and throwing it. Looking at the console class, you'll also find a lot of places with similar code: int errorCode = m
{ publicabstractvoid Execute (); }All commands such as start or stop are inherited from this abstract class: class Startcommander:commander { publicoverridevoid Execute () { // start } } class Stopcommander:commander { public overridevoid Execute () { // stop } }After using polymorphism, the code that invokes the method should look like this: Static void Main (string[] args) {
other types. If you combine too many types, it means that the current class is likely to do too many things, and it needs to be split into two classes. Inheritance does not have such an attribute, in C #, a subclass can have only one base class (the interface releases this restriction, and subclasses inherit from multiple interfaces).The use of inheritance or composition should be considered according to the actual situation. In general, the combination can be more satisfying for most applicati
synchronization took only 0.55 milliseconds, while parallelism used 3.3 milliseconds to complete the work.Now, to simulate getting the loop body to do more, change the loop body in the DoSomething method from 10 to 10000000. The result of the operation is:Synchronization time: 00:00:01.3059138Concurrent Time: 00:00:00.6560593When the loop body needs to do more work, we find that synchronization takes 1.3 seconds to complete the work, while in parallel the work is done in only 0.6 seconds.Turn f
Recommendation 35: Use default to specify an initial value for a generic type variableSome algorithms, such as the Find algorithm for generic collection list Public T func() { null; return t; }Cannot convert null to type parameter ' T ' because it may be a non-nullable value type. Consider using "Default (T)" instead. Public T func() { 0; return t; }The type "int" cannot be implicitly converted to "T".So the above code
{//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
as much as possible during the actual coding process.A static generic method in a non-generic type looks close to the example, but a generic method in a non-generic style does not generate a different type in the local code at run time.As follows: classMyList {Static intcount; Public Static intFunc() { returncount++; } } Static voidMain (string[] args) {Console.WriteLine (Mylist.funcint>()); Console.WriteLine (Mylist.funcint>()); Console.WriteLine
if two threads are used, the output is 12 according to the logic of the program.In this code, if you let Localinit return a value of 0, you might never notice the trap:() = { return0; Now, to understand this trap more clearly, let's use this better-understood code:Static voidMain (string[] args) { string[] Stringarr =New string[] {"AA","BB","cc","DD","ee","FF", "GG","hh" }; stringresult =string. Empty; Parallel.Forstring> (0, Stringarr.length, () ="-", (i, Lo
traversal is parallel, not sequential. So, here's a tip: if our output has to be synchronous or must be sequential, then parallel should not be used.The Foreach method is primarily used to handle parallel operations of generic collection elements, as follows: static void Main (string [] args) {List int > nums = new listint > {1 , 2 , 3 , 4 }; Parallel.ForEach (Nums, (item) => {Console.WriteLine ( " Some work code for collection element {0} ... " The output is:Some wor
); Console.readkey (); Cts. Cancel (); Console.readkey (); } Static voidtasksended (task[] tasks) {Console.WriteLine ("All tasks are complete! "); } The output of the above code is:Task begins ...Task begins ...Task begins ...All tasks have been completed (canceled)!This recommendation shows how task (Task) and TaskFactory (Task Factory) are used. Task further optimizes the scheduling of the background thread pool and speeds up the processing of threads. So in the FCL 4.0 era, if yo
=NewClassshoulddisposebase ("Method1"); METHOD2 (); } finally{c.dispose (); } } Static voidMethod2 () {classshoulddisposebase C=NULL; Try{C=NewClassshoulddisposebase ("Method2"); } finally{c.dispose (); } }Output:In method: Method2 is released!In method: Method1 is released!Finally does not terminate because of an exception that exists in the call stack, and the CLR executes the catch block before executing the finally block. As follows:
) { thrownew dataaccessexception (); } }The same is true for SQLite's data access layer. The business layer code at the beginning of this article can be changed to: Iuserdal dal = dataaccess.createuserdal (); Try { = dal. Getoneuser (); } Catch (DataAccessException ex) { // Handling Data connection exception }Turn from: 157 recommendations for
searching for a second element that satisfies the condition and returning from the collection. If a collection contains a lot of elements, this kind of query can bring us considerable time efficiency.Like the first method, the take method receives an integer parameter, and then we return the number specified by the parameter. As with first, it returns directly from the current iteration, rather than waiting for the entire iteration to complete before it satisfies the condition. If a collection
; }} disposed=true; } Public voidSamplepublicmethod () {if(disposed) {Throw NewObjectDisposedException ("Anothersampleclass","Anothersampleclass is disposed"); } //omitted } }Type Anothersampleclass Although it does not contain any explicit unmanaged resources, because it contains a non-trivial type, we still have to implement a standard dispose pattern for it.In addition, a type has a native resource (that is, an unmanaged resource) and it should inherit the IDispos
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
)); Dynamic Dynamicsample=Newdynamicsample (); Stopwatch WATCH2=stopwatch.startnew (); for(inti =0; I ) {Dynamicsample.add (1,2); } Console.WriteLine (string. Format ("Dynamic time: {0} milliseconds", Watch2. Elapsedmilliseconds)); The output is:Reflection Time: 2575 msDynamic Time: 76 msAs can be seen, there is no optimized reflection implementation, the above loop execution efficiency is much lower than the performance of the dynamic implementation. If the reflection implementation is optimiz
iterations to the UI: Private New MyList (); Private Imyenumerator enumerator = list. GetEnumerator (); while (Enumerator. MoveNext ()) { int current = Enumerator. Current; Console.WriteLine (current. ToString ()); }Business Class B to implement a new iterator for the collection object, for one of its own needs: Private New as MyList); as MyList). Setenumerator (Enumerator2); while (Enumerator2. MoveNext ())
heartbeat data to determine the online situation on the controlled side. The usual practice is to maintain a model quantity, if in an acceptable block time (such as 500ms) heartbeat data transmission failure, then the control thread will not receive a signal, that is, can judge the short-term status of the controlled side. In this case, it is usually meaningless to record each socketexception.If you do not know how to handle an exception, then do not "eat" the exception, if you accidentally "ea
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.