反射从DLL中的所有类型获取值

时间:2014-12-02 20:52:44

标签: c# reflection

我正在尝试加载DLL,并为每种类型显示属性名称和值。我有以下代码,它抛出一个System.Reflection.TargetException,消息“对象与目标类型不匹配”。

var DLL = Assembly.LoadFrom(PathToDLL);
                foreach (Type type in DLL.GetTypes())
                {
                    foreach (PropertyInfo property in type.GetProperties())
                    {
                        lstProperties.Items.Add(string.Format("{0} - {1}", property.Name, property.GetValue(DLL, null)));
                    }
                }

我尝试使用类型,DLL和null与GetValue()调用,我做错了什么?

我正在测试的DLL有一个属性:

public string TheValue{ get; set; }

谢谢大家。

1 个答案:

答案 0 :(得分:2)

扩展评论,以下是他们所谈论的一个例子。

在DLL中:

public class TheClass
{
    public string TheValue { get; set; }
}

创建类的实例并设置属性值:

TheClass cls = new TheClass();
cls.TheValue = "hello!";

然后更改代码以引用您创建的实例:

lstProperties.Add(string.Format("{0} - {1}", property.Name, property.GetValue(cls, null)));