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、运行结果