当前位置:网站首页>C foundation 8-reflection and dependency injection
C foundation 8-reflection and dependency injection
2022-07-28 20:55:00 【W.C.Zeng】
Reflection
Reflection can occur when the loader is running , Get and load assemblies dynamically , And you can get the information of the assembly
Reflection is to get classes dynamically at run time 、 object 、 Method 、 Object data is an important means
Mainly used class libraries :System.Reflection
Core class :
- Assembly Describes the assembly
- Type Describes the type of class
- ConstructorInfo Describes the constructor
- MethodInfo Describes all the methods
- FieldInfo Describes the fields of the class
- PropertyInfo Describes the properties of the class
Through the above core classes, you can dynamically obtain the classes in the assembly at run time , And execute class construction to generate class objects , Get the field or property value of the object dynamically , It can also dynamically execute class methods and instance methods .
Here is B standing c sharp Teacher Liu tiemn The first phase Dependency injection 、 Reflection in relevant chapters , An example of a toy program that simulates the sound of small animals .
The developer announced SDK ( dll ) 、 One store MOD file ( dll ) The catalog of And toy program
Other developers quote SDK , The small animals developed by ourselves (dll) Put in storage MOD In the directory of the file , Run the toy program provided by the developer , This expands the content of the toy program
SDK
The developer announced a SDK To other developers , Including a feature and a small animal interface
namespace sdk;
public class UnfinishedAttribute : Attribute
{
}
If other developers write code for small animals to make noises , Not yet completed , Add this attribute to the class
Just like this.
namespace Animals1;
using sdk;
[Unfinished]
public class Bird : IAnimal
{
public void Voice(int times)
{
for (int i = 0; i < times; i++)
{
System.Console.WriteLine(" Serge ");
}
}
}
The purpose of using the interface is to restrict the small animal classes written by developers , There must be a way to make a sound Voice
namespace sdk;
public interface IAnimal
{
void Voice(int times);
}
Then developers publish their sdk.dll
Use SDK
As a developer , Use CLI Create a command line program Name it Animals1, We should quote the developers' share in the project DLL Reference through assembly
Notice the file path ..\sdk.dll
modify Animal1.csproj Project profile , Add reference
...
<ItemGroup>
<Reference Include="sdk">
<HintPath>..\sdk.dll</HintPath>
</Reference>
</ItemGroup>
...
Write a calf
namespace Animals1;
using sdk;
// [Unfinished]
public class Cow : IAnimal
{
public void Voice(int times)
{
for (int i = 0; i < times; i++)
{
System.Console.WriteLine(" Moo ");
}
}
}
Construction Engineering , Generated Animals1.dll Assembly of
Suppose that the developer requires MOD Files in Animals Under the table of contents , Then put Animals1.dll Copy to the directory
Toy program
In the toy program that simulates animal calls , There is a small animal list , The user enters the corresponding number on the command line , Call... In the linked list The first n A little animal , Make a cry m Time
This requires dynamic loading Animals All under directory DLL file , Judge whether the class inside implements IAnimal Interface , Make sure there is a way to make a sound , And judge the characteristics of the class , There is no sign of UnfinishedAttribute features , Just add the small animals inside to the linked list .
Introducing class library , Developers can directly introduce SDK engineering
// introduce assembly.GetTypes
using System.Reflection;
// introduce AssemblyLoadContext
using System.Runtime.Loader;
using sdk;
Define the small animal list
var folder = Path.Combine(Environment.CurrentDirectory, "Animals");
var files = Directory.GetFiles(folder);
var animalsTypes = new List<Type>();
Dynamic loading DLL , Add the small animals released by the developer to the small animal list
foreach (var file in files)
{
// Load assembly
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file);
// Get reflection
var types = assembly.GetTypes();
foreach (var t in types)
{
// As long as there's a way Just add
// if (t.GetMethod("Voice") != null)
// {
// animalsTypes.Add(t);
// }
// Use SDK If there are settings Hang in the air characteristic , Do not add
if (t.GetInterfaces().Contains(typeof(IAnimal)))
{
// Access to features
var ifUnfinished = t.GetCustomAttributes(false).Any(a => a.GetType() == typeof(UnfinishedAttribute));
if (ifUnfinished)
{
continue;
}
animalsTypes.Add(t);
}
}
}
Processing user input
while (true)
{
try
{
for (int i = 0; i < animalsTypes.Count; i++)
{
System.Console.WriteLine($"{
i + 1},{
animalsTypes[i].Name}");
}
System.Console.WriteLine("==================\nchoice animal 1~ ? hit 0 to break;");
int index = int.Parse(Console.ReadLine());
if (index == 0)
{
break;
}
if (index > animalsTypes.Count || index < 1)
{
System.Console.WriteLine("error index");
continue;
}
System.Console.WriteLine("How many times ?\nhit 0 to break;");
int times = int.Parse(Console.ReadLine());
if (times == 0)
{
break;
}
var t = animalsTypes[index - 1];
var m = t.GetMethod("Voice");
var o = Activator.CreateInstance(t);
// change to the use of sth. SDK
// m.Invoke(o, new object[] { times });
var a = o as IAnimal;
a.Voice(times);
}
catch (System.Exception)
{
throw;
}
}
Print the results
Input in sequence
2 enter
3 enter
exit enter
notice 2 The little dog barked 3 Time , The code of kitten and puppy is the same as that of calf , It can be constructed separately Animal2.dll Put in Animals Under the table of contents
1,Cat
2,Dog
3,Cow
==================
choice animal 1~ ? hit 0 to break;
2
How many times ?
hit 0 to break;
3
Wang
Wang
Wang
1,Cat
2,Dog
3,Cow
==================
choice animal 1~ ? hit 0 to break;
exit
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Int32.Parse(String s)
c# How the program references external DLL
Internal library ( Libraries of other projects under the same solution ), Just use the command line tool directly add reference Quote other projects
External libraries , Need to use csc Command line tools , Link the library and compile
csc /out:xxxxx.exe /reference:xxx.dll xxxxx.cs
Another way is to modify the project file directly json After profile , Re execution dotnet restore Automatically download the modified dependencies
{
"dependencies": { //nuget Dependency package
"EntityFramework": "6.1.3",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.Dnx.Runtime": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"PimProject.Common": "1.0.0"
},
"frameworks": {
"dnx451": {
"dependencies": {
},
"frameworkAssemblies": { // Reference is made here to external dll file
"System.Data": "4.0.0.0"
}
}
},
"dotnet": {
"dependencies": {
"System.Data.SqlClient": "4.0.0-rc2-23530",
"System.Data": "4.0.0"
}
},
"version": "1.0.0-*",
"description": "Class Library",
"authors": [ "sadams" ],
"tags": [ "" ],
"projectUrl": "",
"licenseUrl": ""
}
Another method is the one mentioned earlier in this article “ Use SDK” It's about , Manually edit the project configuration file of the project
边栏推荐
- 【1331. 数组序号转换】
- Dynamic planning: code summary of knapsack problem template
- Random talk on GIS data (VI) - projection coordinate system
- [工具类] Map的util包, 常用 实体类转化为map等操作
- Explain the mobile control implementation of unity in detail
- Easynlp Chinese text and image generation model takes you to become an artist in seconds
- Explain the life cycle function in unity in detail
- Redis 3.0源码分析-数据结构与对象 SDS LIST DICT
- 漂亮的蓝色背景表单输入框样式
- How to balance security and performance in SQL?
猜你喜欢

Introduction to redis II: RedHat 6.5 installation and use

作业 ce

Explain rigid body and collider components in unity

How do we do full link grayscale on the database?

Redis 3.0源码分析-数据结构与对象 SDS LIST DICT

一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力

Explain the camera in unity and its application

Integrating database Ecology: using eventbridge to build CDC applications

JS win7 transparent desktop switching background start menu JS special effect

Network shell
随机推荐
"When you are no longer a programmer, many things will get out of control" -- talk to SUSE CTO, the world's largest independent open source company
Huawei cloud digital asset chain, "chain" connects the digital economy, infinite splendor
Report redirect after authorized login on wechat official account_ The problem of wrong URI parameters
Space shooting Lesson 16: props (Part 2)
prometheus配置alertmanager完整过程
Three steps to teach you unity serial communication
Classes and objects (medium)
不懂就问,快速成为容器服务进阶玩家!
融合数据库生态:利用 EventBridge 构建 CDC 应用
使用ORDER BY 排序
《软件设计师考试》易混淆知识点
C reads the data in the CSV file and displays it after importing the DataTable
Learn about the native application management platform of rainbow cloud
How do we do full link grayscale on the database?
漂亮的蓝色背景表单输入框样式
Unity typewriter teaches you three ways
十七年运维老兵万字长文讲透优维低代码~
Unity package exe to read and write excel table files
JS chart scatter example
Oracle库访问很慢,是什么原因?