Entity validation in C)

Source: Internet
Author: User
Entity validation in C)

Environment:

Windows 2008, vs 2008 SP1, ASP. net mvc 1.0

I. It may be the most primitive Verification Code

To make the problem as simple as possible, let's take a simple user class.

Now we need to add a method in the user class to verify the validity of the user instance. I believe many people have written the following similar code:

The check () method simply applies various rules for the attributes of the user class, and then returns an invalid prompt information set.

During verification, you can simply call the check () method of the object:

Okay, I admit, this method seems to be enough in general, but many people may be crazy when they see a series of IF Statements. Yeah, I don't like it either, then try to eliminate them in the most even way.

Ii. New Features Based on C #3.0

To eliminate if, consider using a line to link those verification rules, so:

The Extension Method for compiling entity classes is as follows:

The check () method of the object is changed:

In this way, we use the extension method to eliminate if, but we link the verification rules and throw illegal entity information in an abnormal way. Therefore, each verification can only obtain one verification message, this is obviously not in line with the actual situation. Think about it ..

Iii. Continue Evolution

To obtain a set of verification error messages, improve the following:

To make the Code look more like this, add a base class to the object, which is called entitybase.

Then write a verification class:

Then, let's take a look at the modified check () method. The function of this verification class is clear at a glance:

Don't explain it? In fact, it is also linked up, and a set of verification error messages are returned to see the results:

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.