当前位置:网站首页>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 .
边栏推荐
- [staff] the direction of the symbol stem and the connecting line (the symbol stem faces | the symbol stem below the third line faces upward | the symbol stem above the third line faces downward | the
- About DNS
- 2022-2028 global manual dental cleaning equipment industry research and trend analysis report
- How to develop digital collections? How to develop your own digital collections
- tarjan2
- MongoDB非關系型數據庫
- Pychart creates new projects & loads faster & fonts larger & changes appearance
- Delphi xe10.4 installing alphacontrols15.12
- AcWing 245. Can you answer these questions (line segment tree)
- Possible causes of runtime error
猜你喜欢
Face++ realizes face detection in the way of flow
Systemserver service and servicemanager service analysis
[JSON] gson use and step on the pit
QT implementation interface jump
Render header usage of El table
GB/T-2423. XX environmental test documents, including the latest documents
多线程查询,效率翻倍
CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
GB/T-2423.xx 环境试验文件,整理包括了最新的文件里面
Deployment practice and problem solving of dash application development environment based on jupyter Lab
随机推荐
2022 low voltage electrician test question simulation test question bank simulation test platform operation
QT implementation interface jump
STM32__05—PWM控制直流电机
2022-2028 global wood vacuum coating machine industry research and trend analysis report
The number one malware in January 2022: lokibot returned to the list, and emotet returned to the top
PMP personal sprint preparation experience
Tupu software has passed CMMI5 certification| High authority and high-level certification in the international software field
What are the common proxy servers and what are the differences?
Yyds dry goods inventory accelerating vacuum in PG
Analysis of FLV packaging format
2022低压电工考试题模拟考试题库模拟考试平台操作
Mongodb non relational database
Mmsegmentation series training and reasoning their own data set (3)
New programmer magazine | Li Penghui talks about open source cloud native message flow system
How to create an instance of the control defined in SAP ui5 XML view at runtime?
[learn C and fly] 1day Chapter 2 (exercise 2.2 find the temperature of Fahrenheit corresponding to 100 ° f)
結婚後
Ten minutes will take you in-depth understanding of multithreading - multithreaded teamwork: synchronous control
Remote connection to MySQL under windows and Linux system
【做题打卡】集成每日5题分享(第二期)