Custom attribute is used to record information irrelevant to the object in this province.

Source: Internet
Author: User

I thought of a simple example. This is an example of adding people as friends.

By default, A and B are friends. If B is enthusiastic or prefers to make friends, A will automatically add A friend. If B doesn't like making friends too much, then B will be one-way.

These habits actually have nothing to do with the object. in C #, additional information can be recorded through Attrubute (feature.

Here is a piece of code.

1. Define attributes

Namespace Test
{

[AttributeUsage (AttributeTargets. Class)]
Public class extends ricattribute: System. Attribute
{
Public parameter ricattribute ()
{

}
}

}

2. Define type

Public class Person
{
Private string m_Name;
Private Person m_person;


Public Person (string name)
{
This. m_Name = name;
}


Public virtual Person Friend
{
Get
{
If (m_person! = Null)
{
Return m_person;
}
Else
{
Return new Person ("NoFriend ");
}
}
Set
{
M_person = value;
// Append a friend
Response ricattribute att = System. Attribute. GetCustomAttribute (value. GetType (), typeof (Response ricattribute) as response ricattribute;
If (att! = Null)
{
Value. Friend = this;
}
}
}

Public override string ToString ()
{
Return this. m_Name;
}

}

 
[Symmetric]
Public class SpecialPerson: Person
{
Public SpecialPerson (string name): base (name)
{
}
}

Call:

Person c = new Person ("Person ");
SpecialPerson p = new SpecialPerson ("Person B ");
C. Friend = p;

Console. WriteLine (p. Friend. ToString ());
Console. WriteLine (c. Friend. ToString ());

P is more enthusiastic, so they will be friends with each other.

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.