当前位置:网站首页>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 .
边栏推荐
- Baohong industry | what misunderstandings should we pay attention to when diversifying investment
- 【无标题】
- Ten minutes will take you in-depth understanding of multithreading - multithreaded teamwork: synchronous control
- Provincial election + noi Part IV graph theory
- 結婚後
- 实现一个自定义布局的扫码功能
- After marriage
- C # use system data. The split mixed mode assembly is generated for the "v2.0.50727" version of the runtime, and it cannot be loaded in the 4.0 runtime without configuring other information
- 设置状态栏颜色
- What is the principle of bone conduction earphones and who is suitable for bone conduction earphones
猜你喜欢
寻找重复数[抽象二分/快慢指针/二进制枚举]
Render header usage of El table
Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
Is bone conduction earphone better than traditional earphones? The sound production principle of bone conduction earphones is popular science
2022-2028 global wood vacuum coating machine industry research and trend analysis report
A list of job levels and salaries in common Internet companies. Those who have conditions must enter big factories. The salary is really high
Golang configure export goprivate to pull private library code
Face++ realizes face detection in the way of flow
超图iServer rest服务之feature查询
[staff] pitch representation (treble clef | C3 60 ~ B3 71 pitch representation | C4 72 pitch representation | C5 84 pitch representation)
随机推荐
图扑软件通过 CMMI5 级认证!| 国际软件领域高权威高等级认证
[learn C and fly] 3day Chapter 2 program in C language (exercise 2.3 calculate piecewise functions)
Jointly developed by nailing, the exclusive functions of glory tablet V7 series were officially launched
Addition without addition, subtraction, multiplication and division (simple difficulty)
V-model of custom component
Force deduction daily question 540 A single element in an ordered array
Realize the code scanning function of a custom layout
[pit] how to understand "parameter fishing"
[liuyubobobo play with leetcode algorithm interview] [00] Course Overview
CoordinatorLayout + TabLayout + ViewPager2(里面再嵌套一个RecyclerView),RecyclerView的滑动冲突解决
About DNS
[JSON] gson use and step on the pit
3048. Number of words
Mathematics in Sinorgchem: computational geometry
MMSegmentation系列之训练与推理自己的数据集(三)
Qualcomm platform WiFi -- P2P issue (2)
Delphi xe10.4 installing alphacontrols15.12
Qualcomm platform WiFi -- Native crash caused by WiFi
The basic steps of using information theory to deal with scientific problems are
SAP ui5 beginner tutorial 19 - SAP ui5 data types and complex data binding