[C #] Attribute ),

Source: Internet
Author: User

[C #] Attribute ),

If a programmer is a cat, which one are you a cat?

This is a technology that I have always liked. It is neither difficult nor difficult to understand. It works with reflection. You can't think of anything you can't do (exaggerated ).

Application Scope

Assembly, module, type (class, structure, enumeration, interface, delegate), field, method (including constructor), method, parameter, method return value, property, Attribute

  

[AttributeUsage (AttributeTargets. all)] public class TestAttribute: attribute {} [testattrict] // structure public struct TestStruct {} [testattrict] // enumerate public enum TestEnum {} [TestAttribute] // public class TestClass {[TestAttribute] public testClass () {} [TestAttribute] // FIELD private string _ testField; [TestAttribute] // attribute public string TestProperty {get; set;} [TestAttribute] // [return: testattrition] // define the return value in public string TestMethod ([TestAttribute] string testParam) // {throw new NotImplementedException ();}}View Code

Here we provide the definition of Atrribute, which is commonly used in addition to programming sets and modules.

 

Custom Attribute

To comply with the "CLS" requirements, all custom attributes must inherit System. Attribute.

Step 1: customize an Attribute to check the string length

    [AttributeUsage(AttributeTargets.Property)]    public class StringLengthAttribute : Attribute    {        private int _maximumLength;        public StringLengthAttribute(int maximumLength)        {            _maximumLength = maximumLength;        }        public int MaximumLength        {            get { return _maximumLength; }        }    }

AttributeUsage is an Attribute provided by the system to limit the scope of the custom Attribute. Here, we only allow this Attribute to be applied to the Property and create a constructor with parameters, specifies the maximum length required for external input.

Step 2: Create an object class to run our custom attributes

 public class People    {        [StringLength(8)]        public string Name { get; set; }        [StringLength(15)]        public string Description { get; set; }    }

Two string fields, Name and Description, must be 8 characters in length and 15 characters in length.

Step 3: Create a verified class

Public class ValidationModel {public void Validate (object obj) {var t = obj. getType (); // because we only set attivity in Property, we first get Property var properties = t. getProperties (); foreach (var property in properties) {// only perform a stringlength verification here. If you need to perform a lot of verification here, make a good design, do not use if elseif to link/it will be very difficult to maintain. There are many open-source projects like this. if you are interested, you can look at the source code. If (! Property. isDefined (typeof (StringLengthAttribute), false) continue; var attributes = property. getCustomAttributes (); foreach (var attribute in attributes) {// MaximumLength here is best to use constants for var maxinumLength = (int) attribute. getType (). getProperty ("MaximumLength "). getValue (attribute); // obtain the attribute value var propertyValue = property. getValue (obj) as string; if (propertyValue = null) throw new Exception ("exception info"); // you can customize it here, you can also use the specific system exception class if (propertyValue. length> maxinumLength) throw new Exception (string. format ("the length of the {0} value {1} exceeds {2}", property. name, propertyValue, maxinumLength ));}}}}View Code

Reflection is used here, because Attribute is generally used together with reflection, which verifies whether the length of the string exceeds the required value. If it exceeds the value, an exception is thrown.

Private static void Main (string [] args) {var people = new People () {Name = "qweasdzxcasdqweasdzxc", Description = "description"}; try {new ValidationModel (). validate (people);} catch (Exception ex) {Console. writeLine (ex. message);} Console. readLine ();}View Code

 

The basic article does not involve many advanced usage. After understanding this, there will be many changes.

 


What is c/o in the address information?

C/o: care of transferred...

C/O:
Abbr. 1. = care of transferred by... (letter term );
2. = carried over [accounting] Carry forward to the next page; transfer delivery (exchange term );
3. = cash order [accounting] refers to the promissory notes, pay-as-you-go tickets, cash bills, and cash orders.

[C Language] Is there a function that can clear keys in the cache?

Fflush (stdin)
Clear standard input Cache

# Include "stdio. h"
Main ()
{
Char a, B;
Scanf ("% c", & );
// Fflush (stdin );
Scanf ("% c", & B );
Printf ("\ n % c", a, B );
}

You can try it. If there is no fflush (stdin), if you enter a string of characters "abcd", a = 'A', B = 'B'
If fflush (stdin) exists, after entering "abcd", the program continues to wait for the input, and then enters "efdfsd". The result is a = 'A', B = 'E'

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.