【发布时间】:2019-07-15 09:06:38
【问题描述】:
我正在学习 C# 中的反射,通过修改它的工具,我能够创建一些代码:
- 从文件加载 DLL 程序集
- 从程序集中获取公共静态类类型
- 从类中获取公共静态属性的 PropertyInfo
- 获取/设置属性值
我在 Visual Studio 2019 中编写代码,解决方案是一个简单的 WPF 应用程序和一个 DLL,两者都是用 C# 编写的。
设置和获取属性值的代码块:
int Number = int.Parse(InputBox.Text);
Assembly MyDll = Assembly.LoadFile(@"D:[...]\WPFapp\ClassLibrary\bin\Debug\ClassLibrary.dll");
Type TestType = MyDll.GetType("ClassLibrary.Class1");
PropertyInfo PropInfo = TestType.GetProperty("Number");
PropInfo.SetValue(null, Number);
Assembly MyDll = Assembly.LoadFile(@"D:[...]\WPFapp\ClassLibrary\bin\Debug\ClassLibrary.dll");
Type TestType = MyDll.GetType("ClassLibrary.Class1");
PropertyInfo PropInfo = TestType.GetProperty("Number");
DiffAssemblyBox.Text = PropInfo.GetValue(null).ToString();
DLL:
namespace ClassLibrary
{
public static class Class1
{
public static int Number {get; set;}
}
}
上面的代码运行,我制作了应用程序,因此用户输入的数字将被发送到 DLL 并返回。但是,当我尝试发送它时,它会在 SetValue 处引发 System.NullReferenceException。我尝试调试,似乎TestType类型正确设置为类,但PropInfo为null。
感谢您的帮助
【问题讨论】:
-
您需要使用
GetProperty重载,以便您可以使用BindingFlagssee link 。您需要指定BindingFlags.Static。
标签: c#