该属性对象的值与 C# 中的目标类型不匹配(使用反射获取属性值)

本文关键字:属性 获取 不匹配 反射 目标 对象 类型 | 更新日期: 2023-09-27 18:37:20

我有一个包含此属性的类。

public List<string> Messages { get; set; }

我想使用反射读取该属性的值。

List<string> messages = new List<string>();
PropertyInfo prop = myType.GetProperty("Messages");
var message = prop.GetValue(messages);

但是我收到此错误:

"对象与目标类型不匹配。"

我用了这行:

var message = prop.GetValue(messages,null);

而不是

var message = prop.GetValue(messages);

但我仍然得到同样的错误。

该属性对象的值与 C# 中的目标类型不匹配(使用反射获取属性值)

属性

信息包含有关消息属性的元数据。可以使用该属性信息在该类型的某个实例上获取或设置该属性的值。这意味着您需要将要从中读取属性Messages的类型的实例传递到 GetValue 调用中:

messages = (List<string>)prop.GetValue(instanceOfMyType);

以下是您要执行的操作的工作示例:

class A
{
    public List<string> Messages { get; set; }
    public static void Test()
    {
        A obj = new A { Messages = new List<string> { "message1", "message2" } };
        PropertyInfo prop = typeof(A).GetProperty("Messages");
        List<string> messages = (List<string>)prop.GetValue(obj);
    }
}

仅供记录,此实现在现实生活中毫无意义,因为您可以直接通过obj.Messages获取值