当前位置:网站首页>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 .
边栏推荐
- 2022-2028 global wood vacuum coating machine industry research and trend analysis report
- Qualcomm platform WiFi -- P2P issue (2)
- V-model of custom component
- Xiaomi, a young engineer, was just going to make soy sauce
- Kibana controls es
- Systemserver service and servicemanager service analysis
- Yyds dry goods inventory accelerating vacuum in PG
- 只需简单几步 - 开始玩耍微信小程序
- [learn C and fly] 2day Chapter 8 pointer (practice 8.1 password unlocking)
- 2022-2028 global nano abrasive industry research and trend analysis report
猜你喜欢

Addition without addition, subtraction, multiplication and division (simple difficulty)

MongoDB非關系型數據庫

【JVM】创建对象的流程详解

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] 3day Chapter 2 program in C language (exercise 2.3 calculate piecewise functions)](/img/8e/a86a9724251718d98ce172a6a96e53.png)
[learn C and fly] 3day Chapter 2 program in C language (exercise 2.3 calculate piecewise functions)

2022-2028 global manual dental cleaning equipment industry research and trend analysis report
![[JVM] detailed description of the process of creating objects](/img/6e/0803b6b63c48337985faae8d5cbe1a.png)
[JVM] detailed description of the process of creating objects

Share the basic knowledge of a common Hongmeng application

Formatting logic of SAP ui5 currency amount display
![[road of system analyst] collection of wrong topics in enterprise informatization chapter](/img/c4/0bb4823ca85c440b4e0587a91b2585.jpg)
[road of system analyst] collection of wrong topics in enterprise informatization chapter
随机推荐
Use the open source project [banner] to achieve the effect of rotating pictures (with dots)
Software testing learning notes - network knowledge
Principle of computer composition - interview questions for postgraduate entrance examination (review outline, key points and reference)
Possible causes of runtime error
[JVM] detailed description of the process of creating objects
Leetcode question brushing (10) - sequential question brushing 46 to 50
Addition without addition, subtraction, multiplication and division (simple difficulty)
Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
tarjan2
[pit] how to understand "parameter fishing"
[punch in questions] integrated daily 5-question sharing (phase II)
CoordinatorLayout + TabLayout + ViewPager2(里面再嵌套一个RecyclerView),RecyclerView的滑动冲突解决
Rotating frame target detection mmrotate v0.3.1 learning model
[staff] diacritical mark (ascending sign | descending sign B | double ascending sign x | double descending sign BB)
Pat a-1165 block reversing (25 points)
Share the basic knowledge of a common Hongmeng application
【做题打卡】集成每日5题分享(第二期)
[staff] pitch representation (treble clef | C3 60 ~ B3 71 pitch representation | C4 72 pitch representation | C5 84 pitch representation)
PMP personal sprint preparation experience
How does proxy IP participate in the direct battle between web crawlers and anti crawlers