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, rather than writing the variable name in the code. 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 through the anonymous type and obtain its internal attributes through reflection.
Static void main ()
{
String testVar1 = "testName ";
Console. WriteLine (new {testVar1}. GetVariableName ());
Int testVar2 = 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.
& Nb