System.Reflection.TargetException: Object does not match target type
异常通常发生在尝试通过反射调用方法或设置属性时,传递了一个与目标类型不兼容的对象实例。以下是关于这个问题的基础概念、原因、解决方案以及相关应用场景的详细解释。
反射(Reflection) 是 .NET 框架中的一个功能,它允许程序在运行时检查和操作类型、方法、属性等。通过反射,可以在运行时创建对象、调用方法和访问属性。
PropertyInfo.SetValue 方法用于设置属性的值。它需要两个参数:一个是对象实例,另一个是要设置的值。
System.Reflection.TargetException: Object does not match target type
异常通常由以下原因引起:
SetValue
方法的对象实例与属性所属的类型不匹配。null
。确保传递给 SetValue
方法的对象实例与属性所属的类型完全匹配。
public class ExampleClass
{
public string ExampleProperty { get; set; }
}
ExampleClass instance = new ExampleClass();
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("ExampleProperty");
propertyInfo.SetValue(instance, "New Value"); // 正确
如果属性是静态的,应该使用 null
作为对象实例参数。
public class ExampleClass
{
public static string StaticExampleProperty { get; set; }
}
PropertyInfo staticPropertyInfo = typeof(ExampleClass).GetProperty("StaticExampleProperty");
staticPropertyInfo.SetValue(null, "New Static Value"); // 正确
在调用 SetValue
之前,确保对象实例不为 null
。
ExampleClass instance = new ExampleClass();
if (instance != null)
{
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("ExampleProperty");
propertyInfo.SetValue(instance, "New Value");
}
else
{
Console.WriteLine("Instance is null.");
}
反射在以下场景中非常有用:
以下是一个完整的示例,展示了如何正确使用反射设置属性值:
using System;
using System.Reflection;
public class ExampleClass
{
public string ExampleProperty { get; set; }
}
public class Program
{
public static void Main()
{
try
{
ExampleClass instance = new ExampleClass();
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("ExampleProperty");
if (propertyInfo != null)
{
propertyInfo.SetValue(instance, "New Value");
Console.WriteLine($"Property value set to: {instance.ExampleProperty}");
}
else
{
Console.WriteLine("Property not found.");
}
}
catch (TargetException ex)
{
Console.WriteLine($"TargetException: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
}
通过以上步骤和示例代码,可以有效避免 System.Reflection.TargetException: Object does not match target type
异常,并正确使用反射机制。
领取专属 10元无门槛券
手把手带您无忧上云