当前位置:网站首页>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 .
边栏推荐
- New programmer magazine | Li Penghui talks about open source cloud native message flow system
- Cache processing scheme in high concurrency scenario
- Start a business
- The video number will not be allowed to be put on the shelves of "0 yuan goods" in the live broadcasting room?
- LeetCode刷题(十)——顺序刷题46至50
- Special symbols in SAP ui5 data binding syntax, and detailed explanation of absolute binding and relative binding concepts
- MMSegmentation系列之训练与推理自己的数据集(三)
- buu_ re_ crackMe
- Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market
- 【做题打卡】集成每日5题分享(第二期)
猜你喜欢

AcWing 245. Can you answer these questions (line segment tree)

超图iServer rest服务之feature查询

LeetCode刷题(十)——顺序刷题46至50

The capacity is upgraded again, and the new 256gb large capacity specification of Lexar rexa 2000x memory card is added

Which brand of running headphones is good? How many professional running headphones are recommended

GB/T-2423.xx 环境试验文件,整理包括了最新的文件里面

只需简单几步 - 开始玩耍微信小程序

Baohong industry | four basic knowledge necessary for personal finance

CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
![[liuyubobobo play with leetcode algorithm interview] [00] Course Overview](/img/1c/c8cab92c74b6658c3ef608c5255f1f.png)
[liuyubobobo play with leetcode algorithm interview] [00] Course Overview
随机推荐
Ten minutes will take you in-depth understanding of multithreading - multithreaded teamwork: synchronous control
小米青年工程师,本来只是去打个酱油
Mathematics in Sinorgchem: computational geometry
[staff] pitch representation (bass clef | C1 36 note pitch representation | C2 48 note pitch representation | C3 60 note pitch representation)
How to develop digital collections? How to develop your own digital collections
4. Find the median of two positive arrays
[Chongqing Guangdong education] Sichuan University concise university chemistry · material structure part introductory reference materials
Unit · elementary C # learning notes
[reading notes] programmer training manual - practical learning is the most effective (project driven)
LFM信号加噪、时频分析、滤波
[road of system analyst] collection of wrong topics in enterprise informatization chapter
Baohong industry | 6 financial management models at different stages of life
MVVM and MVC
Delphi xe10.4 installing alphacontrols15.12
[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
Remote connection to MySQL under windows and Linux system
自定义组件的 v-model
OSPF LSA message parsing (under update)
2022-2028 global encryption software industry research and trend analysis report
Query word weight, search word weight calculation