characteristic
In C#, Attributes are a mechanism to add metadata to code. This metadata can be read by the compiler at compile time, or by reflection at runtime. Features provide a flexible way to add comment information and can affect the behavior of the code.
Definition of features
Features are derived fromClass of class.
You can create custom features or use predefined features provided by the .NET Framework.
concept
Features are essentially a special use of classes, and they are used for the following purposes:
- Provides additional information for code elements (such as classes, methods, properties, etc.).
- Instructs the compiler or runtime to perform specific operations.
Purpose
The main purposes of the characteristics include:
- Metadata provision: Features allow developers to provide metadata for program entities (such as types, methods, properties, etc.). These metadata can be read by reflection at runtime for various purposes such as configuration, serialization, verification, etc.
-
Compile-time processing: Certain features can change the behavior of the compiler. For example,
ObsoleteAttribute
A class or member can be marked as outdated, and the compiler will issue a warning when using these outdated elements in the code. - Runtime processing: The running time can read characteristic information through reflection, thereby changing the behavior of the program. For example, characteristics are used to process routing information, controller and operation method selection, etc.
- Code documentation: Features can be used to generate documents, such as XML document files, which can be used by document generation tools such as Sandcastle to create API documents.
- Code Analysis: Features can be used in code analysis tools to provide feedback on code quality, performance, and practice.
Usage features:
Using features usually involves the following steps:
-
Define features: Create an inherited from
class and use
AttributeUsageAttribute
to specify the usage rules of the feature. - Application Features: Apply features to code elements, such as classes, methods, properties, etc.
- Reading Features: At runtime, reflection is used to read characteristic information.
Define features:
Features are derived fromClass of class. You can define your own attributes to mark elements in your program. For example:
[AttributeUsage( | , AllowMultiple = false)] public class MyCustomAttribute : Attribute { public string Description { get; } public MyCustomAttribute(string description) { Description = description; } }
Application Features:
Once a feature is defined, it can be applied to classes, methods, properties, fields, interfaces, parameters, etc.
[MyCustom("Description of this class")] public class MyClass { public void MyMethod() { // Method implementation } }
Usage features:
You can use reflection at runtime to check the existence of a feature and read its information.
var type = typeof(MyClass); var attribute = <MyCustomAttribute>(); if (attribute != null) { ($"describe: {}"); }
Predefined features:
The .NET Framework provides many predefined features, such as:
-
ObsoleteAttribute
: Class or member marked as outdated. -
ConditionalAttribute
: The method is executed only when a specific symbol is defined. -
AttributeUsageAttribute
: Control how custom features are used.
reflection
In C#, reflection is a powerful mechanism that allows a program to check and manipulate its own structure and behavior at runtime.
Reflection provides a way in which programs can access and process internal information of types, members, modules, and assembly (Assemblies) in an assembly.
definition
Reflection is a feature in the .NET Framework that allows a program to get type information at runtime (not at compile time). This information includes the name of the type, member, base class, implemented interfaces, generic parameters, etc.
concept
The core concepts of reflection include:
-
Type (Type):
Class represents the type in the CLR (Common Language Runtime). Each type defined in .NET is implicitly associated with one
Type
Object association. - Assembly: An assembly is an executable file (.exe or .dll) containing type definitions and resources.
- Members: Including fields, properties, methods, constructors, events, and nested types.
- Metadata: Information stored in the assembly that describes types and members.
Purpose
The main purposes of reflection include:
- Dynamically create objects: Create an instance of the type at runtime without knowing the specific type at compile time.
- Dynamically call members: Calling methods, properties, fields, and events of types at runtime.
- Provide metadata: Provide detailed information about program elements for the compiler and runtime, which can be used for code analysis, code generation, serialization and deserialization, etc.
- Supports general programming: Reflection is the basis for implementing generic and dynamic language runtime (DLR), which allows writing more flexible and general code.
- Supports testing and debugging tools:Reflection can be used to develop debuggers, test frameworks, and code analysis tools that require checking and manipulating the internal structure of the program.
- Implement dependency injection:Reflection is a key technology for implementing dependency injection (DI) containers, which allows for dynamic parsing and injection of dependencies at runtime.
The main functions of reflection include
- Type Check: Determine the type of the object at runtime.
- Type creation: Create an instance of type at runtime.
- Member visits: Access methods, properties, fields, and events of types.
- Member calls: Call a method of type or access its properties and fields.
- Get type information: Get complete information about the type, including its members and modifiers.
Basic steps to using reflection
-
Get type information:use
Type
Class represents information about type. Can be passedtypeof
Keyword orMethod Getting
Type
Object. -
Create an instance:use
Method creates an instance of type.
-
Visit members:pass
Type
Objects obtain member information, such as methods, properties, fields, etc. - Calling members: Call methods or access fields and properties using the obtained member information.
Sample code:
using System; using ; public class ReflectionExample { public void Display() { ("Method Call"); } public static void Main() { // Get type information Type myType = typeof(ReflectionExample); // Create an instance of type object myObject = (myType); // Get and call the method MethodInfo displayMethod = ("Display"); (myObject, null); // Get and set field values FieldInfo myField = ("myField", | ); if (myField != null) { (myObject, "Value set by reflection"); } // Get and set property values PropertyInfo myProperty = ("myProperty"); if (myProperty != null) { (myObject, "Attribute value is set by reflection"); } } private string myField; public string myProperty { get; set; } }
The relationship between characteristics and reflection
The relationship between characteristics and reflection is mainly reflected in the following aspects:
-
Get feature information: Through reflection, the program can read characteristic information at runtime. This is through
Type
ClassicGetCustomAttributes
A method implemented, the method can return all feature instances applied to a specific program element (such as type, method, attribute, etc.). - Dynamic behavior: Reflection allows the program to dynamically change behavior based on characteristic information. For example, it is determined whether to execute a method based on the characteristics on the method, or how to serialize an object based on the characteristics on the class.
- Metadata Driver: Many frameworks and libraries (such as Entity Framework, Unity, etc.) use reflection to read feature information to achieve metadata-driven design. These frameworks configure and guide their internal behavior through features.
- Code flexibility and scalability: Features and reflections provide a non-invasive way to extend the code. Developers can change the behavior of programs by adding or modifying features without modifying existing code.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.