欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > C#用反射机制调用dll文件的字段、属性和方法

C#用反射机制调用dll文件的字段、属性和方法

2025/5/6 21:59:44 来源:https://blog.csdn.net/qq_27474555/article/details/140204038  浏览:    关键词:C#用反射机制调用dll文件的字段、属性和方法

1、创建dll文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace CLStudent
{public class Student{//字段public string Name = "Tom";//属性public double ChineseScore { get; set; } = 80;public double MathScore { get; set; } = 90;//方法public double TotalScore(double cScore,double mScore){double score = cScore + mScore;return score;}}
}

2、调用dll

using System.Reflection;namespace ReflectionApp
{internal class Program{static void Main(string[] args){//方法一:用指定的名称加载程序集//1、添加程序集的引用//2、加载程序集//Assembly assembly = Assembly.Load("CLStudent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");//Assembly assembly = Assembly.Load("CLStudent");//方法二:用指定的路径加载程序集Assembly assembly = Assembly.LoadFile("F:\\Winform\\ReflectionApp\\CLStudent\\bin\\Debug\\CLStudent.dll");//Assembly assembly = Assembly.LoadFrom("F:\\Winform\\ReflectionApp\\CLStudent\\bin\\Debug\\CLStudent.dll");//方法三:用指定的文件名加载程序集//1、添加程序集的引用//2、加载程序集//Assembly assembly = Assembly.LoadFrom("CLStudent.dll");Type type = assembly.GetType("CLStudent.Student");object StudentInstance = Activator.CreateInstance(type);FieldInfo fieldInfo = type.GetField("Name");string fieldValue = (string)fieldInfo.GetValue(StudentInstance);Console.WriteLine($"Student Name 字段值为{fieldValue}");PropertyInfo propertyInfo = type.GetProperty("ChineseScore");double propertyValue = (double)propertyInfo.GetValue(StudentInstance);Console.WriteLine($"Student {fieldValue} ChineseScore值为{propertyValue}");propertyInfo = type.GetProperty("MathScore");propertyValue = (double)propertyInfo.GetValue(StudentInstance);Console.WriteLine($"Student {fieldValue} MathScore值为{propertyValue}");MethodInfo methodInfo = type.GetMethod("TotalScore");object output = methodInfo.Invoke(StudentInstance, new object[] { 100,90 });Console.WriteLine($"Student TotalScore 方法返回值为{output}");Console.ReadKey();}}
}

3、运行结果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词