A demo of Custom Attributes

Source: Internet
Author: User
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. reflection; // use reflection

Namespace Cui. useattribute
{
// Apply the attributeusage feature to control the usefulness of this feature
[Attributeusage (attributetargets. All, allowmultiple = false, inherited = true)]
Public class myattribute: attribute // must inherit from Attribute Class
{
Private string _ username; // User Name
Private string _ lastlogintime; // Last Logon Time
Private string _ remark; // remarks

Private myattribute (){}

Public myattribute (string username, string lastlogintime)
{
This. _ username = username;
This. _ lastlogintime = lastlogintime;
}

Public String Username
{
Get {return _ username = NULL? "Username is null": This. _ username ;}
}
Public String lastlogintime
{
Get {return _ lastlogintime ;}
}
Public String remark
{
Get {return _ remark = NULL? "Remark is null": _ remark ;}
Set {_ remark = value ;}
}

Public override string tostring ()
{
Return string. Format ("username: {1} {0} lastlogintime: {2} {0} remark: {3} {0} {0 }",
Environment. newline, this. username, this. lastlogintime, this. remark );
}


}

[My ("Jie", "2008-05-06", remark = "Hello, I'm Jie.")]
Public class usemyattribute
{
Public void saysomething ()
{
Console. writeline ("Say something ");
}
}

Public class test
{
Public static void main ()
{
Type type = typeof (usemyattribute );
Myattribute = attribute. getcustomattribute (type, typeof (myattribute) as myattribute;

If (myattribute! = NULL)
{
Console. writeline ("username: {0}", myattribute. username );
Console. writeline ("lastlogintime: {0}", myattribute. lastlogintime );
Console. writeline ("remark: {0}", myattribute. remark );
Console. writeline ();
}

Object OBJ = activator. createinstance (typeof (usemyattribute ));
Methodinfo MI = type. getmethod ("saysomething ");
Mi. Invoke (OBJ, null );


Console. readkey (true );
}
}
}

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.