在C#中的反思:从DLL获取静态属性

时间:2019-07-15 09:06:38

标签: c#

我正在学习C#中的反射,并且通过修补其工具,我能够创建一些代码来实现:

  1. 从文件加载DLL程序集
  2. 从程序集中获取公共静态类类型
  3. 从类中获取公共静态属性的PropertyInfo
  4. 获取/设置属性值

我正在用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为空。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

获取如下所示的静态属性,然后尝试

Type TestType = MyDll.GetType("ClassLibrary.Class1");
var field = TestType.GetProperty("Number ", BindingFlags.Public | BindingFlags.Static);

基本上,您必须使用BindingFlags才能获得在此处有用的静态属性。

相关问题