【问题标题】:Object does not match target type PropertyInfo SetValue - one class to another对象与目标类型 PropertyInfo SetValue 不匹配 - 一个类到另一个类
【发布时间】:2014-12-09 20:38:18
【问题描述】:

所以我有 2 个类,它们都有相同的属性名称。一类包含不同的变量:intstringsboolDateTime 第二类仅包含 1 个 int,其余均为字符串。

现在我想遍历所有属性,从 class1 中获取值,加密该数据并将其保存为 obj2 中的字符串,然后将其返回到主窗体(稍后将其保存在数据库中)。

public PersoonEncrypted EncryptPersonClass(Class1 object1)
    {
        PersoonEncrypted persEncrypt = new PersoonEncrypted(); //second class obj

        Type type = object1.GetType();
        PropertyInfo[] properties = type.GetProperties();
        Type type2 = persEncrypt.GetType();
        PropertyInfo[] properties2 = type.GetProperties();
        foreach (var bothProperties in properties.Zip(properties2, (obj1, obj2) => new { Obj1 = obj1, Obj2 = obj2 }))
        {
            string value = "";

            value = bothProperties.Obj1.GetValue(object1) as string;
            if (!string.IsNullOrWhiteSpace(value))
            {
                string encryptValue = Encrypt(value);
                if ((bothProperties.Obj2 != null) && (bothProperties.Obj2.PropertyType == typeof(string)))
                { //!= null check has no effect at all
                    bothProperties.Obj2.SetValue(persEncrypt, encryptValue, null); //errorLine
                }
            }

        }

        return persEncrypt;
    }

这是我到现在为止的想法。 当然,我已经搜索了其他解决方案like this one。在应用了一些自己的更改之后,它没有返回任何错误,但它没有将任何加密字符串保存到类 persEncrypt 中。我从那个测试中得出的结论是,它正在测试特定属性的第二类(在我的示例中为persEncrypt)中的值是否为空,虽然它不应该那样做,但它应该创建一个新实例该变量并将其保存在对象类中,但删除该检查给了我同样的错误。

【问题讨论】:

    标签: c# reflection types propertyinfo setvalue


    【解决方案1】:
    • 你只是.Zip-ing 两个 PropertyInfo 对象列表,它只是遍历两个列表,而不检查或排序任何类型的匹配。根据属性出现的顺序,这可能会导致错误行为 - 请考虑使用 .Join 来匹配属性名称。
    • 此代码在尝试将其分配给没有索引器之前不会检查属性上的索引器 - 任何类型为 string 的索引属性都会到达这一点,然后在您尝试设置时抛出异常它。
    • 由于此代码调用Properties,因此属性本身的代码可能会引发异常。在这里,您的异常中的 StackTrace 可以揭示更多关于正在发生的事情。
    • 您的代码还会直接检查 string 类型的属性 - 使用反射时,您应该使用 IsAssignableFrom 来代替以允许继承类型,尽管在这种情况下这不太可能成为问题。

    【讨论】:

    • 我明天会检查 join 方法,看起来是一个很好的解决方案,如果它有效,我会提供答案,除非同时其他人足够快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多