. Net uses custom class attribute instances,. net instances

Source: Internet
Author: User

. Net uses custom class attribute instances,. net instances

In general, you can use Type. GetCustomAttributes in. net to obtain the custom attributes of the class. You can use PropertyInfo. GetCustomAttributes to obtain the custom attributes of the property information.
 
The following describes how to use ing object classes of a simple database table based on custom class attributes and custom class attributes, you can easily tag classes and attributes in a class.
 
Create a custom Attribute for the class to identify the table name in the database and inherit the custom Attribute class:

Copy codeThe Code is as follows: [AttributeUsage (AttributeTargets. Class, Inherited = false, AllowMultiple = false)]
Public sealed class TableAttribute: Attribute
{
Private readonly string _ TableName = "";
Public TableAttribute (string tableName)
{
This. _ TableName = tableName;
}
Public string TableName
{
Get {return this. _ TableName ;}
}
}

Create a custom Attribute for the Attribute to identify the name of the field in the database table and inherit from the Attribute class:

Copy codeThe Code is as follows: [AttributeUsage (AttributeTargets. Property, Inherited = false, AllowMultiple = false)]
Public class FieldAttribute: Attribute
{
Private readonly string _ FieldName = ""; // database field name
Private System. Data. DbType _ Type = System. Data. DbType. String; // The Field Type of the database.
 
Public fieldattriname (string fieldName)
{
This. _ FieldName = fieldName;
}
 
Public FieldAttribute (string fieldName, System. Data. DbType type)
{
This. _ FieldName = fieldName;
This. _ Type = type;
}
 
Public string FieldName
{
Get {return this. _ FieldName ;}
}
 
Public System. Data. DbType Type
{
Get {return this. _ Type ;}
}
}
 
Create a data entity base class:

Copy codeThe Code is as follows: public class BaseEntity
{
Public BaseEntity ()
{
}
 
/// <Summary>
/// Obtain the table name
/// </Summary>
/// <Returns> </returns>
Public string GetTableName ()
{
Type type = this. GetType ();
Object [] objs = type. GetCustomAttributes (typeof (TableAttribute), true );
If (objs. Length <= 0)
{
Throw new Exception ("the entity class does not identify the TableAttribute attribute ");
}
Else
{
Object obj = objs [0];
TableAttribute ta = (TableAttribute) obj;
Return ta. TableName; // get the table name
}
}
/// <Summary>
/// Obtain FieldAttribute on the data entity class
/// </Summary>
/// <Param name = "propertyName"> </param>
/// <Returns> </returns>
Public FieldAttribute GetFieldAttribute (string propertyName)
{
PropertyInfo field = this. GetType (). GetProperty (propertyName );
If (field = null)
{
Throw new Exception ("property name" + propertyName + "nonexistent ");
}
Object [] objs = field. GetCustomAttributes (typeof (fieldattrites), true );
If (objs. Length <= 0)
{
Throw new Exception ("" + propertyName + "fielfielfielfielfiel ");
}
Else
{
Object obj = objs [0];
FieldAttribute fieldAttribute = (FieldAttribute) obj;
FieldAttribute. FieldValue = field. GetValue (this, null );
Return fieldAttribute;
}
}
}
 
Create a data entity:

Copy codeThe Code is as follows: [Table ("Wincms_Dictionary")] // ing to the Wincms_Dictionary Table of the database
Public class Wincms_Dictionary: BaseEntity
{
Private int _ DictionaryId;
 
Public Wincms_Dictionary ()
{
}
 
[Field ("DictionaryId", DbType. Int32)] // maps fields to the Wincms_Dictionary table of the database.
Public int DictionaryId
{
Get {return this. _ DictionaryId ;}
Set
{
This. _ DictionaryId = value;
}
}
}
 
/// Obtain the table name and field name corresponding to the object based on the object class
Public class Test
{
 
Public static void main (string [] args)
{
Wincms_Dictionary dict = new Wincms_Dictionary ();
Console. WriteLine ("table name:" + GetTableName (dict ));
Console. WriteLine ("field name:" + GetFieldName (dict, "DictionaryId "));
Console. Read ();
}
 
/// Obtain the object table name
Public static string GetTableName (BaseEntity entity)
{
Return entity. GetTableName ();
}
 
/// Obtain the object field name
Public static string GetFieldName (BaseEntity entity, string propertyName)
{
FieldAttribute fieldAttribute = entity. GetFieldAttribute (propertyName );
Return fieldattriname. FieldName;
}
}
Output result:

Copy codeThe Code is as follows: Table Name: Wincms_Dictionary
Field name: DictionaryId

I hope this article will help you with the. net program design.


C # how to add methods to attributes of a custom class

Class className
Public int sum (int a, int B)
{
Return a + B;
}

Reference: className. sum (1, 2)

How to use C # Custom Attributes

You can use attributes to add instructions to classes, properties, and methods at design time, and then check them by reflecting information at runtime. This article describes how to use C # custom attributes during application development. This article can be downloaded from a technical article, including a Visual Studio project example file using custom attributes. Attribute classes are special document classes that can be used for classes, properties, and methods during design. Attribute classes provide a way to describe certain attributes of an element or determine the behavior of other classes attached to the element, so that these descriptions and behaviors can be accessed and verified at runtime. You can view attribute classes as a way to add special modifiers to class members. For example, if you have ever written a Web service, you must use the WebMethod attribute to make the method public throughout the service. This is a good example of demonstrating the property application, because we need to extend the programming model with the WebMethod property. In C #, there is no built-in method to specify that a method is visible through the Web Service (because the internal establishment indicates that a method is private ), therefore, you must add the WebMethod attribute to meet this requirement. The process of designing custom attributes is very simple. Before designing a property, you only need to consider the following aspects: What is the purpose of using the property? Attributes can be used in many ways. You need to define what functions attributes need to accomplish and ensure that these specific functions are not built in the. NET Framework set. Using the. NET modifier is better than using properties because it simplifies the integration process with other accessories. What information must the attribute store? Is the attribute intended to indicate a simple identifier of a function? Or do attributes need to store information? A property can have a set of information assigned during design and view the information at runtime. For example, let's take a look at the alias attributes in the example application. Which accessories should the attribute reside in? In most cases, attributes can be included in accessories that use these attributes. However, it is better to place attributes in public, feather-level, and shared accessories. This type of configuration allows customers to use properties without referencing unwanted accessories. Which accessories will recognize attributes? If there is no module read attribute, it will be worthless. You may put the class that reads the attribute in the same assembly where the attribute resides. However, as mentioned above, you want to put the methods and attributes for reading attributes in different accessories. Public string SSN {get {return _ ssn;} set {_ ssn = value ;}} is a more complex example. Assume that we have an attribute called "Alias ". The task of this attribute is to check whether a property may have an alias. This allows you to map a property value to another property even if the batch roperty name does not match. This property accepts a series of string values as the ing name. (List B) List B [Alias ("FirstName", "First")] public string FName {get {return _ fName;} set {_ fName = value ;}} in this example, property "FName" is mapped to "FirstName" and "First". Please refer to the example application for more details. Public Alias (params string [] names) {this. names = names;} public string [] Names {get {return _ names;} set {_ names = value ;}} as you can see, this is a common class. The only exception is that it inherits from System. attribute Class. We don't need to do anything special to make it a class. We simply define a required constructor and create a property and a private member that stores the data. List D is a simpler Attribute-"Hide. This property... the remaining full text>

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.