当前位置:网站首页>C reflection practice
C reflection practice
2022-07-02 02:59:00 【FanJiangDaoHaizZ】
Preface
majority Program Both Handle data , Include read 、 Write 、 operation and Show data .( graphics It's also A kind of data Of form .) However , about some Program Come on , they operation Of data No Numbers 、 Text or graphics , It is Program and Program type In itself Of Information . of Program And its type Of data go by the name of element data ( metadata), they preservation stay Program Of Program focus . Program stay Runtime , Sure see other Program Set or Its In itself Of element data . One function Of Program see In itself Of element data or other Program Of element data Of Behavior be called Reflection ( reflection).
Reflection practice
One . Make assembly
open vs Create a new class library 
Click next to configure the path and name of the class library 
After creation, add the following code , One created in the code Example class , Add some fields 、 attribute 、 And methods , And marked him with custom features MyAttribute, For future testing
using System;
namespace MyDll
{
// Specify that custom attributes can only be attached to classes
[AttributeUsage(AttributeTargets.Class)]
public sealed class MyAttributeAttribute : System.Attribute
{
public string Description;
public string Version;
public string ReviewId;
public MyAttributeAttribute(string desc, string ver)
{
Description = desc;
Version = ver;
}
}
[MyAttribute("MyClass", "1.0", ReviewId = "58946")]
public class Example
{
public int a = 567;
private int b = 555;
public int B
{
get
{
return b;
}
set
{
b = value;
}
}
public void HelloDll()
{
Console.WriteLine("HelloDll");
}
public void PrintOut(string s)
{
Console.WriteLine(s);
}
}
}
After adding the code Using shortcut keys ctr + b Generate MyDll.dll file , At this point, we can in the project MyDll\bin\Debug\netcoreapp3.1 Found under folder MyDll.dll file , Indicates that the generation was successful
Two . test
newly build C# Console Application , Run the test code as follows
// Load assembly
Assembly assembly = Assembly.LoadFrom(@"D:\STu\csharp_-study\CSharp_Study\MyDll\bin\Debug\netcoreapp3.1\MyDll.dll");
Type type = assembly.GetType("MyDll.Example");
// Create type real columns
object obj = Activator.CreateInstance(type);
// Calling method
type.GetMethod("HelloDll").Invoke(obj,null);
// Call a method with parameters
type.GetMethod("PrintOut").Invoke(obj, new object[] {
"DLLTEST" });
// get attribute
PropertyInfo propertyInfo = type.GetProperty("B");
// Set field value
propertyInfo.SetValue(obj,444);
Console.WriteLine(propertyInfo.GetValue(obj, null));
// Get field
FieldInfo fieldInfo = type.GetField("a");
// Set field value
fieldInfo.SetValue(obj, 123);
Console.WriteLine(fieldInfo.GetValue(obj));
Console.WriteLine("================ Get all features ====================");
object[] typeAttributes = type.GetCustomAttributes(false); // obtain Example Class
foreach (object attribute in typeAttributes)
{
Console.WriteLine("Attributes description is " + attribute.ToString());
// Access to features Description Information
Console.WriteLine($"Description:{
attribute.GetType().GetField("Description").GetValue(attribute)}");
}
// Get all members
Console.WriteLine("================ Get all members ====================");
MemberInfo[] memberInfos = type.GetMembers();
foreach(var item in memberInfos)
{
Console.WriteLine(item.Name);
}
// Get all fields ( Default public , You can set BindingFlags)
Console.WriteLine("================ Get all fields ====================");
FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (var item in fieldInfos)
{
Console.WriteLine(item.Name);
}
// Get all properties
Console.WriteLine("================ Get all properties ====================");
PropertyInfo[] properties = type.GetProperties();
foreach(var item in properties)
{
Console.WriteLine(item.Name);
}
The output is as follows 
matters needing attention
Relationship with Assembly.LoadFrom Methods can be found in MSDN
About Type class :
1) about Program in be used Of every last type , CLR Metropolis establish One contain This type Information Of Type type Of object .
2) Program in be used Of every last type Metropolis relation To Independent Of Type class Of object .
3) No matter establish Of type Yes How many? individual example , Only One Type object Meeting relation To All of these example .
Abstract
Daniel M·Solis. C# Illustrated tutorial ( The first 4 edition )( Turing books ) (p. 481). People's post and Telecommunications Press . Kindle edition .
边栏推荐
- [JVM] detailed description of the process of creating objects
- [untitled]
- Principle of computer composition - interview questions for postgraduate entrance examination (review outline, key points and reference)
- 批量检测url是否存在cdn—高准确率
- GB/T-2423. XX environmental test documents, including the latest documents
- Addition without addition, subtraction, multiplication and division (simple difficulty)
- Learning notes of software testing -- theoretical knowledge of software testing
- C return multiple values getter setter queries the database and adds the list return value to the window
- Unit · elementary C # learning notes
- What is the difference between an intermediate human resource manager and an intermediate economist (human resources direction)?
猜你喜欢

Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market

STM32__05—PWM控制直流电机

el-table的render-header用法

What is the principle of bone conduction earphones and who is suitable for bone conduction earphones

STM32__ 05 - PWM controlled DC motor

2022-2028 global aluminum beverage can coating industry research and trend analysis report

Analysis of FLV packaging format
![[JVM] detailed description of the process of creating objects](/img/6e/0803b6b63c48337985faae8d5cbe1a.png)
[JVM] detailed description of the process of creating objects

CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
![[learn C and fly] 2day Chapter 8 pointer (practice 8.1 password unlocking)](/img/2e/8fe55393ccca6663d98c0b3dd9a146.png)
[learn C and fly] 2day Chapter 8 pointer (practice 8.1 password unlocking)
随机推荐
2022-2028 global deep sea generator controller industry research and trend analysis report
2022-2028 global manual dental cleaning equipment industry research and trend analysis report
2022-2028 global encryption software industry research and trend analysis report
QT实现界面跳转
旋转框目标检测mmrotate v0.3.1 学习模型
Which brand of sports headset is better? Bluetooth headset suitable for sports
Query word weight, search word weight calculation
2022-2028 global aluminum beverage can coating industry research and trend analysis report
【无标题】
2022 hoisting machinery command examination paper and summary of hoisting machinery command examination
连通块模板及变式(共4题)
设置状态栏颜色
Build a modern data architecture on the cloud with Amazon AppFlow, Amazon lake formation and Amazon redshift
Qualcomm platform WiFi -- Native crash caused by WiFi
Es interview questions
Kibana controls es
tarjan2
What is the difference between an intermediate human resource manager and an intermediate economist (human resources direction)?
[learn C and fly] 4day Chapter 2 program in C language (exercise 2.5 generate power table and factorial table
[question 008: what is UV in unity?]