System.Reflection.TargetException 在 employee.GetType().GetProperty(property.Name)

System.Reflection.TargetException on employee.GetType().GetProperty(property.Name)

我遇到了一个我似乎无法弄清楚的问题。我确定对此有一个简单的解释,但我不明白为什么我得到 System.Reflection.TargetException: 'Object does not match target type' 当我尝试从(在这种情况下)获取 属性员工对象。

employee.GetType().GetProperty(property.Name)

搜索错误 returns 许多结果描述了调用 Set/GetValue 方法的问题,但我还没有找到解决这个问题的方法。

我在抛出异常的地方设置了一个断点,它表明 property.Name 确实是一个值 - 并且是对象的真实 属性。我也尝试过手动指定一个我知道存在的 属性。还是一样。

有什么建议吗?

编辑:改为尝试以下操作:

Type type = typeof (Employee); //Throws the TargetException
PropertyInfo theProperty = type.GetProperty(property.Name);

现在在上面的第一行抛出相同的异常。

编辑:添加了有关我正在构建的应用程序的代码和更多详细信息。

Class Employee 的定义(为了简化到 JSON 数据的映射,这个 class "represents",class/fields 是挪威语 - 这是format/language 数据进来了,抱歉 :-))

"Ansatt" = 员工。 "Ansattnummer" = 员工编号

[JsonObject]
public class Ansatt
{
    public int Ansattnummer { get; set; }
    public string Fornavn { get; set; }
    public string Etternavn { get; set; }
    public int Pin { get; set; }
    public string Adresse { get; set; }
    public int Postnummer { get; set; }
    public string Poststed { get; set; }
    public int TlfPrivat { get; set; }
    public int MobilTlf { get; set; }
    public string EpostAdresse { get; set; }
    public DateTime Fodt { get; set; }
}

我的应用程序从 Web 服务中检索给定的数据集 - 它可能是员工、项目或其他一些可能的数据集。要获取的数据在运行时由用户决定。用户还可以通过 URL-查询指定哪些部分,例如he/she 想要的数据集的列。该程序然后使用所选数据创建一个 csv 文件。

这是我为此使用的代码:

 if (records != null && records.Count != 0) //records contains the chosen dataset - in this case Employees (Ansatt).
                {
                    if (records.GetType() == typeof (List<Ansatt>))
                    {
                        foreach (var model in records as List<Ansatt>)
                        {
                            var temp = new Ansatt();

                            foreach (var property in model.GetType().GetProperties())
                            {

                                var currentProperty = model.GetType().GetProperty(property.Name);

                                if (currentProperty != null)
                                {
                                    Type type = typeof (Ansatt); //Throws System.Reflection.TargetException: 'Object does not match target type'
                                    PropertyInfo tempProperty = type.GetProperty(property.Name);
                                    tempProperty.SetValue(temp, currentProperty.GetValue(property.Name));
                                }
                            }

                            csv.WriteRecord(temp);

                        }
                    }

                }

您需要指定 属性

的名称
PropertyInfo value = employee.GetType().GetProperty("Name");

为了通过反射获取对象的属性,请确保属性名称为public,getter和setter否则它将 return 为空。

例如。

public class Employee
{
   public string YouProperty { get; set; }
}

var employee = new Employee();

var result = employee.GetType().GetProperty("YouProperty");

// The result is property info

请阅读一些信息here

随着MSDN的发展,你应该这样使用它:

class MyClass {
    private int myProperty;
    // Declare MyProperty. 
    public int MyProperty {
        get {
            return myProperty;
        }
        set {
            myProperty = value;
        }
    }
}

public class MyTypeClass {
    public static void Main(string[] args) {
        try {
            // Get the Type object corresponding to MyClass.
            Type myType = typeof(MyClass);
            // Get the PropertyInfo object by passing the property name.
            PropertyInfo myPropInfo = myType.GetProperty("MyProperty");
            // Display the property name.
            Console.WriteLine("The {0} property exists in MyClass.", myPropInfo.Name);

            // Instantiate MyClass
            var myObject = new MyClass()
            {
                MyProperty = 5
            };

            // Get value using reflection
            Console.WriteLine("My property value for my object is {0}.", myPropInfo.GetValue(myObject));

        } catch (NullReferenceException e) {
            Console.WriteLine("The property does not exist in MyClass." + e.Message);
        }
    }
}

对于您的代码,当您想要获取对象实例的 属性 值时,您应该将对象作为引用传递给 PropertyInfo.GetValue(object) 函数。 而不是这个:

tempProperty.SetValue(temp, currentProperty.GetValue(property.Name));

这样做:

tempProperty.SetValue(temp, currentProperty.GetValue(model));