C # small tips

Source: Internet
Author: User

After learning and using C # For so long, I have some experience and lessons to share with you. Here are some tips for C # development:

1. Name of the output variable.

Requirement: Sometimes we may want to input the value of a variable along with its own name to the screen or other places during testing or practice, insteadCodeVariable name. For example:

VaR A = 10;

Console. writeline ("Var name: A, value: {0}", );

Implementation: There are two ways to implement this function. Readers may also consider whether there are other better ways to implement this function.

A. I will first provide the implementation method through anonymous type and reflection.

Public   Static   Class Objectextensions
{
Public   Static   String Getvariablename < T > ( This T OBJ)
{
System. reflection. propertyinfo [] objgettypegetproperties = OBJ. GetType (). getproperties ();

If (Objgettypegetproperties. Length =   1 )
Return Objgettypegetproperties [ 0 ]. Name;
Else
Throw   New Argumentexception ( " Object must contain one Property " );
}
}

// Call method. We construct an object using an anonymous type and obtain its internal attributes through reflection.
Static   Void Main ()
{
String Testvar1 =   " Testname " ;
Console. writeline ( New {Testvar1}. getvariablename ());

IntTestvar2= 12345;
Console. writeline (New{Testvar2}. getvariablename ());
}

B. Use the Lamda expression in. NET 3 to provide a more convenient implementation method.

Static   Void Writename < T > (Expression < Func < T > Expression)
{
Console. writeline ( " {0} = {1} " ,
(Memberexpression) expression. Body). Member. Name,
Expression. Compile ()());
}
Static   Void Main ()
{
String Testvar1 =   " Testname " ;
Writename (() => Testvar1 );
}

2. String Conversion to basic type

Requirement: in daily programming, we often need to convert some string variables to common types in files or user input interfaces. Of course, we can use system. convert class to complete this work, but if there is a lot of conversion work, this kind of code looks very inconvenient, at this time we can pass. net to easily complete this work.

Implementation: through the extension method, reflection and generics can easily complete this task.

Public   Static   Class Objectextensions
{
Static T ? To < T > ( This   String Parse)
Where T: Struct
{
Type T =   Typeof (T );
If (T =   Typeof ( Int ))
{
Int I;
If ( Int . Tryparse (PARSE, Out I ))
Return (T )( Object ) I;
Return   Null ;
}
If (T =   Typeof ( Double ))
{
Double I;
If ( Double . Tryparse (PARSE, Out I ))
Return (T )( Object ) I;
Return   Null ;
}
// Add other types of conversion code, such as datetime, Enum, etc;
Throw   New Notsupportedexception ( String . Format ( " Type: {0} conversion not supported " , T. Name ));
}
}
// Use Functions
Static   Void Main ()
{
Int ? A = " 111 " . < Int > ();
Double ? B = " 111.111 " . < Double > ();
Int ? C = " Bad " . < Int > ();
}

However, because there are two types of conversions in this conversion code that can be compiled, it still looks less comfortable. I hope you can achieve this in a better way.

3. Thread-safe calling components in winform programming.

Requirement: In. NET 1.0, you can directly operate the win form main thread component in other threads, but this also brings potential risks. Therefore, you need to use begininvoke to perform cross-thread operations after 2.0, but this also makes the Code look very slow, sometimes you only need to update a component in the window after a thread operation is completed, such as a progress bar, but you need to write another function to implement it.

Implementation: Drag extension functions and anonymous methods can easily complete the interaction between window threads and other threads. The following provides a simple implementation. Of course, if you need more secure calls, you also need to add some detection measures, such as ishandlecreated detection. If you need to pass parameters, you may need to define another delegate.

Public   Static   Class Controlextention
{
Public   Delegate   Void Invokehandler ();

Public   Static   Void Safeinvoke ( This Control, invokehandler handler)
{
If (Control. invokerequired)
{
Control. Invoke (handler );
}
Else
{
Handler ();
}
}
}

// In form, when you need to operate Component Objects in form in a non-form thread, call the following
Public Form: Form
{
Public Form ()
{
Thread t = New Thread (T1 );
T. Start ();
}
Void T1 ()
{
Thread. Sleep ( 1000 );
This . Safeinvoke (() =>   This . Textbox1.text =   " Hello World " );
}
}

Can this method be called in WPF as above? Since invoke in WPF is changed to dispatcher, the method is slightly different, as shown below:

 Public     Static    Void  Safeinvoke (  This  Control, invokehandler handler)
{
If (Control. Dispatcher. checkaccess ())
{
// The Calling thread owns the dispatcher, and hence the UI element
Handler ();
}
Else
{
// Invokation required
Control. Dispatcher. Invoke (dispatcherpriority. Normal, Handler );
}
}

The above is just some small programming skills that I have encountered or learned from others, hoping to help others. If I have the opportunity, I hope I can make a better summary.

Related Article

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.