Reflection overview-C # features and reflection

Source: Internet
Author: User

Reflection overview-C # features and reflection
One of the tasks of the. NET compiler is to generate metadata descriptions for all defined and referenced types. In addition to the standard metadata in the Assembly, the. NET platform also supports specific attributes to embed more metadata into the assembly. The. NET feature extends the abstract System. Attribute base class.. NET has many predefined features, such as [DllImport], [Obsolete], and [Serializable. Let's look at an example of Obsolete. The Obsolete feature is used to mark unused classes or members. When other programs attempt to access this item, they will receive a warning or error description. Static class StringUtil {public static string ReverseString (string str) {Console. writeLine ("call reverseString"); return "";} [Obsolete ("this legacy method shocould not be used", true)] public static string LegacyReverseString (string str) {Console. writeLine ("call legacyReverseString"); return "" ;}} class Program {static void Main (string [] args) {string str = StringUtil. legacyReverseString ("Hell O World! "); Console. read () ;}} using the above Code, we will receive an error message indicating that we should not use this method. Of course, we can also use code to add custom features. Before starting custom features, we need to know the following concepts. Custom features in code, we can create custom feature types, but this type must be derived directly or indirectly from System. Attribute. The following defines a TableAttribute feature: [AttributeUsage (AttributeTargets. class, Inherited = false, AllowMultiple = false)] public class TableAttribute: Attribute {public TableAttribute () {} public TableAttribute (string tableName) {this. tableName = tableName;} public string TableName {get; set ;}note: it is a Convention to use Attribute suffixes for a feature class name. However, when we add features to a program entity, we can omit the atrri suffix. The compiler first looks for the added feature class in the derived class of System. Attribute. If not, the compiler adds the Attribute suffix to continue searching. For example, when we use it in code, the feature is [Obsolete], but the actual type is ObsoleteAttribute, rather than the Obsolete in the code. When. NET Framework performs name conversion, all. NET features (including custom features) will be suffixed with an Attribute. AttributeUsage in the preceding custom feature, the following code applies the AttributeUsage feature to the custom feature. [AttributeUsage (AttributeTargets. class, Inherited = false, AllowMultiple = false)] The AttributeUsage Class is a predefined feature Class. With this feature, we can control the use of custom features, it describes a custom feature such as and is used. [Serializable] [AttributeUsage (AttributeTargets. class, Inherited = true)] [ComVisible (true)] public sealed class AttributeUsageAttribute: Attribute {public AttributeUsageAttribute (AttributeTargets validOn); public bool AllowMultiple {get; set ;} public bool Inherited {get; set;} public AttributeTargets ValidOn {get;} The Code shows that AttributeUsage has three attributes: ValidOn can be seen from the code that the ValidOn type is System. attributeTarge Ts, and AttributeTargets itself is an enumeration, so that AttributeTargets can be combined by bitwise "or" operations to indicate which program elements are valid. For example, [AttributeUsage (AttributeTargets. assembly | AttributeTargets. class | AttributeTargets. method, Inherited = false, AllowMultiple = false)] the attribute AllowMultiple indicates whether a feature can be repeatedly placed in the same program entity multiple times. The property "Inherited" controls the inheritance rules of custom features, indicating whether the features can be Inherited. From the above introduction, we can see the general steps for creating a custom feature: declare the feature class, which is composed of System. attribute uses the AttributeUsage feature directly or indirectly to control the custom property declaration feature class constructor feature and reflection. When we use the feature, we only add metadata to the Assembly. When combined with reflection, features can play a major role. The following is an example of combining features with reflection. In this example, the Table and Column features are customized, and these features are applied to our User type; then, combine a custom ORM type to convert the Inster () Operation of the object into an SQL statement. Namespace AttributeTest {[AttributeUsage (AttributeTargets. class, Inherited = false, AllowMultiple = false)] public class TableAttribute: Attribute {public TableAttribute () {} public TableAttribute (string tableName) {this. tableName = tableName;} public string TableName {get; set ;}} [AttributeUsage (AttributeTargets. property, Inherited = false, AllowMultiple = false)] public class columnattriple: Att Ribute {public ColumnAttribute () {} public ColumnAttribute (string columnName) {this. columnName = columnName;} public ColumnAttribute (string colunmName, DbType dbType) {this. columnName = colunmName; this. dbType = dbType;} public string ColumnName {get; set;} public DbType {get; set ;}} public class CustomizeORM {public void Insert (object table) {Type type = table. getType (); Dicti Onary <string, string> columnValueDict = new Dictionary <string, string> (); StringBuilder SqlStr = new StringBuilder (); SqlStr. append ("insert into"); TableAttribute tableAttribute = (TableAttribute) type. getCustomAttributes (typeof (TableAttribute), false ). first (); SqlStr. append (tableAttribute. tableName); SqlStr. append ("("); foreach (var prop in type. getProperties () {foreach (var attr in prop. getCus TomAttributes () {string value = prop. GetValue (table). ToString (); ColumnAttribute columnAttribute = attr as ColumnAttribute; if (columnAttribute! = Null) {columnValueDict. add (columnAttribute. columnName, value) ;}}foreach (var item in columnValueDict) {SqlStr. append (item. key); SqlStr. append (",");} SqlStr. remove (SqlStr. length-1, 1); SqlStr. append (") values ('"); foreach (var item in columnValueDict) {SqlStr. append (item. value); SqlStr. append ("','");} SqlStr. remove (SqlStr. length-2, 2); SqlStr. append (")"); Console. writeLine (SqlStr. toS Tring ();} [Table ("Users")] public class User {[Column (ColumnName = "Id", DbType = DbType. int32)] public int UserID {get; set;} [Column (ColumnName = "Name", DbType = DbType. string)] public string UserName {get; set;} [Column (ColumnName = "Age", DbType = DbType. int32)] public int Age {get; set;} class Program {static void Main (string [] args) {CustomizeORM customizeORM = new CustomizeORM (); User use R = new User () {UserID = 1, UserName = "Wilber", Age = 28}; customizeORM. insert (user); Console. read () ;}}from this example, we can see that the metadata added to the Assembly through features can be obtained and used by the reflection program at runtime. Through the IL code, we can see that the feature is simplified. In the code, we use Table and Column to modify the User type, and the Attribute suffix is added to the IL code. At the same time, we can see that, these features are changed to User-type metadata. This article summarizes the. NET features and introduces the basic knowledge required for custom features. The feature itself only adds metadata to the Assembly. when used in conjunction with reflection, these added metadata can play a greater role.

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.