这篇文章介绍了C#反射调用dll文件中的方法操作泛型与属性字段,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、使用方法
查找DLL文件,
通过Reflection反射类库里的各种方法来操作dll文件
二、步骤
加载DLL文件
Assembly assembly1 = Assembly.Load("SqlServerDB");//方式一:这个DLL文件要在启动项目下
string filePath = Environment.CurrentDirectory + "";
Assembly assembly2 = Assembly.LoadFile(filePath + @"\SqlServerDB.dll");//方式二:完整路径
Assembly assembly3 = Assembly.LoadFrom(filePath + @"\SqlServerDB.dll");//方式三:完整路径
Assembly assembly4 = Assembly.LoadFrom(@"SqlServerDB.dll");//方式三:完整路径
获取指定类型
foreach (var item in assembly4.GetTypes())//查找所有的类型,就是有多少个类
{
Console.WriteLine(item.Name);
}
获取构造函数
Type type = assembly4.GetType("SqlServerDB.ReflectionTest");//在ReflectionTest类中调用
foreach (var ctor in type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
Console.WriteLine($"构造方法:{ctor.Name}");
foreach (var param in ctor.GetParameters())
{
Console.WriteLine($"构造方法的参数:{param.ParameterType}");
}
}
//【3】实例化
//ReflectionTest reflectionTest = new ReflectionTest();//这种实例化是知道具体类型--静态
//object objTest = Activator.CreateInstance(type);//动态实例化--调用我们的构造方法
object objTest1 = Activator.CreateInstance(type, new object[] { "string" });//动态实例化--调用我们的有参数构造方法
//调用私有构造函数
//ReflectionTest reflectionTest = new ReflectionTest(); //普通调用
object objTest2 = Activator.CreateInstance(type, true);
调用非构造方法
object objTest2 = Activator.CreateInstance(type, true);
//调用普通方法
ReflectionTest reflectionTest = objTest2 as ReflectionTest;//as转换的好处,它不报错,类型不对的话就返回null
reflectionTest.Show1();
//调用私有方法
var method = type.GetMethod("Show2", BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(objTest2, new object[] { });
调用泛型方法
//泛型无参数
var method3 = type.GetMethod("Show3");//查找指定方法
var genericMethod = method3.MakeGenericMethod(new Type[] { typeof(int) });//指定泛型参数类型T
genericMethod.Invoke(objTest2, new object[] { });
//泛型有参数
var method4 = type.GetMethod("Show4");//查找指定方法
var genericMethod4 = method4.MakeGenericMethod(new Type[] { typeof(string) });//指定泛型参数类型T
genericMethod4.Invoke(objTest2, new object[] { 123, "泛型string参数" });
反射测试类
位于SqlServerDB.dll中的ReflectionTest.cs文件中
/// <summary>
/// 反射测试类
/// </summary>
public class ReflectionTest
{
//私有构造函数
private ReflectionTest()
{
Console.WriteLine("这是私有无参数构造方法");
}
//普通构造函数
//public ReflectionTest()
//{
// Console.WriteLine("这是无参数构造方法");
/
沃梦达教程
本文标题为:C#反射调用dll文件中的方法操作泛型与属性字段
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
猜你喜欢
- user32.dll 函数说明小结 2022-12-26
- Unity3D实现渐变颜色效果 2023-01-16
- Oracle中for循环的使用方法 2023-07-04
- Unity Shader实现模糊效果 2023-04-27
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- 如何使用C# 捕获进程输出 2023-03-10
- c# 模拟线性回归的示例 2023-03-14
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- .NET CORE DI 依赖注入 2023-09-27