C # Custom Properties

Source: Internet
Author: User

Describe

Properties provide a powerful way to associate declarative information with C # code (types, methods, properties, and so on). property is associated with a program entity, you can use a technical query property called reflection at run time.

Attributes appear in two forms:

    • One is a property that is defined in the common language runtime (CLR).

    • The other is a custom property that you can create to add additional information to your code. This information can be retrieved programmatically at a later time.

The role of custom attributes

Sometimes we need to add some attributes or additional information to a class or a member of a class, so that the function of the class or variable can be more clearly controlled finer granularity, a simple analogy: a table in the database, each field in the table has many properties, such as whether the primary key, default value, annotation information, etc., How do we represent this information when we are writing entity classes? This can be achieved through custom attributes.

Steps to implement a custom attribute

1. Declare a class and apply the AttributeUsageAttribute attribute to the class. The name of the class is the name of the new property
2. Declare that the class inherits from System.Attribute:
3. Define the Private field to store the property values:
4. When needed, create a constructor for the property:
5. Define methods, fields, and properties for attributes (Attribute):

Instance one:

attribute classes (and related enumerations)

<summary>
The purpose of the database field.
</summary>
public enum Enumdbfieldusage
{
<summary>
Not defined.
</summary>
None = 0x00,
<summary>
Used for primary keys.
</summary>
PrimaryKey = 0x01,
<summary>
Used for unique keys.
</summary>
UniqueKey = 0x02,
<summary>
The value of the field is controlled by the system.
</summary>
Bysystem = 0x04
}

    [AttributeUsage (Attributetargets.property, inherited = True)]
    Public Class Dbfieldattribute:attribute
    {
        Enumdbfieldusage M_usage;
        string M_strfieldname;
        string m_strdescription;
        object M_defaultvalue;

Public Dbfieldattribute (String strfieldname,object defaultvalue,enumdbfieldusage usage,string strDescription)
{
M_strfieldname = strFieldName;
M_defaultvalue = defaultvalue;
M_usage = usage;
M_strdescription = strdescription;
}

Public Dbfieldattribute (String fieldName): This (Fieldname,null, enumdbfieldusage.none,null)
{ }

        public Dbfieldattribute (string fieldName, Enumdbfieldusage usage): This (fieldName, null,usage, null)
        {}

        
       // Gets the database field name for the member mapping.
        public string FieldName
         {
            get
             {
                 return m_strfieldname;
           }
            Set
             {
                 m_strfieldname = value;
           }
       }

Get the default value for this field
public Object DefaultValue
{
Get
{
return m_defaultvalue;
}
Set
{
M_defaultvalue = value;
}
}
}
This code shows how to make a custom attribute class. In fact, the difference from the general class is that this class inherits from attribute, plus AttributeUsage is an attribute on the property, which is optional.

Data Access Layer entity classes:

Class Dalobj
{
String M_strtablename;
int M_nid;
String M_strname;
String M_password;

Public Dalobj (String strtablename)
{
M_strtablename = strTableName;
}

[Dbfield ("id", Enumdbfieldusage.primarykey)]
public int ID
{
get {return m_nid;}
set {M_nid = value;}
}

[Dbfield ("name", defaultvalue= "visitor")]
public string Name
{
get {return m_strname;}
set {m_strname = value;}
}

[Dbfield ("pwd")]
public string PassWord
{
get {return m_password;}
set {M_password = value;}
}
}
This code demonstrates how to use a custom property. There are two points to note.

First: The class name can be the same as the custom class name, you can add or subtract the following Attribute, this example is used with the custom class name reduced "Attribute".

Second: The property parameter filling method, if the custom attribute class (example Dbfieldattribute) its own constructor with parameters, then these parameters are required, you can overload the constructor to meet different combinations, after the required parameters are filled out, You can continue to assign a name to a public member in a custom attribute class, such as the defaultvalue= "visitor" in the example is named parameter.

To traverse the code of a custom property:

Dalobj dalobj = new Dalobj ("users");
StringBuilder sb = new StringBuilder ();
foreach (PropertyInfo proinfo in Dalobj.gettype (). GetProperties ())
{
object[] Attrs = Proinfo.getcustomattributes (typeof (Dbfieldattribute), true);
if (attrs. Length = = 1)
{
Dbfieldattribute attr = (dbfieldattribute) attrs[0];
Sb. Append (attr. FieldName + ":" + (attr. DefaultValue = = null? "NULL": attr. Defaultvalue.tostring ()) + "\ r \ n");
}
}
MessageBox.Show (sb.) ToString ());
This code shows how to retrieve the value of a custom property, mainly using GetCustomAttributes to get the value of the property.

C # Custom Properties

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.