C # TextBox extension method data verification details

Source: Internet
Author: User

When viewing the company project code, there is a problem: the winform interface has a lot of information to fill in and submit the background server for updates, but the legal verification of data and value conversion are not flattering, after a bunch of if judgments and conversions, I thought about whether I could expand a method, figured out a way of thinking, and recorded it and discussed it with everyone. if there is anything wrong, please correct it.

Design Concept:
1. Because most of the data values are obtained from the TextBox control, you can extend the generic method to obtain the values directly based on the converted data type. Similarly,
Var value = this.txt Sample. GetValue <int> ();

2. You can pass in a delegate to handle the conversion failure operation, and reload this method to provide a default operation.

Okay. Start the job below:
1. Create a TextBox-type Extension Method
Reference to MSDN: the extension method enables you to "add" methods to an existing type without creating a new derived type, re-compiling, or modifying the original type in other ways. An extension method is a special static method, but it can be called like an instance method of an extension type. For client code written in C # and Visual Basic, there is no significant difference between calling an extension method and calling a method actually defined in the type.
Extension methods are defined as static methods, but they are called through the instance method syntax. Their first parameter specifies the type of the method to act on, and the parameter is prefixed with the this modifier. The extension method is in the range only when you use the using command to explicitly import the namespace to the source code.
Note: The extension method is defined inside non-nested and non-generic static classes.

2. because the conversion type is unknown, but it is a value type, it is designed using the generic method, and the strut generic constraints are added, because the operation in case of conversion failure can be customized, therefore, an Action delegate is input for implementation as follows:

Copy codeThe Code is as follows: public static TResult GetValue <TResult> (this TextBox textBox, Action <TextBox> failed)
Where TResult: struct
{
Var type = typeof (TResult );
Var method = type. GetMethod ("TryParse", new Type [] {typeof (string), type. MakeByRefType ()});
Var parameters = new object [] {textBox. Text, default (TResult )};

// If the conversion fails, run failed.
If (! (Bool) method. Invoke (null, parameters ))
{
Failed (textBox );
Throw new InvalidCastException ("the input value format is incorrect. Check the input value. ");
}

Return (TResult) parameters [1];
}

The reflection mechanism is used to call the T. TryParse (string param, out T value) type, such as Int32.TryParse (string param, out Int32 value). Note that:
(1 ). the GetMethod () method must be passed in an appropriate parameter (the signature of the method to be reflected) to determine the unique method. For example, if the method is overloaded (common), otherwise the return value is null, in the method signature, if the parameter contains the ref or out keyword, the Type must be added. makeByRefType (), as shown above.
(2 ). after obtaining a unique method instance, you can pass in the corresponding parameters and call the Invoke method to call the method. MethodInfo. the first parameter of the Invoke (object obj, object [] parameters) method is the object that calls this method through reflection. If it is a static method (for example, this example), you can pass in null, the second parameter is the method parameter, and the order must be consistent with the method signature.
(3). The method parameter contains the ref and out keywords. The obtained value is obtained through the parameter array. In this example, parameters [1]

3. Define the delegate for failed Conversions
C # There are two built-in encapsulated delegation types: Action and Func delegation, and there are many overloaded versions. There can be more than 10 parameters, so you don't have to worry about parameter issues. Among them, the Action delegate has no return value, which belongs to the Void type. The Func delegate has a return value, such as Func <T, TResult>, which is common in the Linq operation. In this example, there is no need to return the value, therefore, the Action delegate is used. Because the operation that fails to be converted needs to be processed, the TextBox is used as the parameter of the Delegate, as shown in the Code. When the conversion fails, it is processed:
// If the conversion fails, run failed.
If (! (Bool) method. Invoke (null, parameters ))
Failed (textBox );
Here is a brief introduction to delegation: Delegation is actually a type. It can be seen through the decompilation tool that when a delegate is constructed, a method will be passed in, in fact, two parameters (target, methodPtr) will be implicitly passed in ), the target parameter is an instance that calls this method. If the static method is used, it is null. methodPtr is the memory address of the incoming method (storing this information in metadata), faild (textBox) on the surface, I am not very familiar with it. Why does the C # compiler actually do a lot of work for us when an object is followed by a parameter? Here it is actually faild. invoke (textBox). In this way, it is better to understand that the delegate is a type, and the method registered by the delegate is called through the delegate object of faild.

4. Create an overloaded version:
Use a lambda expression to define the default conversion failure operation. If the conversion fails, a message is displayed, and all options are selected and located in the input box.

Copy codeThe Code is as follows: public static TResult GetValue <TResult> (this TextBox textBox, bool isShowError)
Where TResult: struct
{
Return GetValue <TResult> (textBox, p =>
{
If (isShowError)
{
P. Focus ();
P. SelectAll ();
MessageBox. Show ("the format of the input value is incorrect. Please enter it again! ",
"Prompt -- Value Type:" + typeof (TResult). Name,
MessageBoxButtons. OK, MessageBoxIcon. Warning );
}
});
}

Copy codeThe Code is as follows: // The default version. Call the previous overload method.

Public static TResult GetValue <TResult> (this TextBox textBox)
Where TResult: struct
{
Return GetValue <TResult> (textBox, true );
}

5. Test the experiment:
Create a winform program. The interface is as follows:

Background code:

Copy codeThe Code is as follows: private void btnConvert_Click (object sender, EventArgs e)
{
Try
{
Var intValue = txtInt. GetValue <int> ();
Var floatValue = txtFloat. GetValue <float> ();
Var dateTimeValue = txtDateTime. GetValue <DateTime> ();
Var doubleValue = txtDouble. GetValue <double> ();
}
Catch (Exception ){}
}

If the input value is invalid, an error is displayed ,:

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.