![](/img/trans.png)
[英]C# Reflection - PropertyInfo.SetValue [Object does not match target type]
[英]Object does not match target type PropertyInfo SetValue - one class to another
所以我有2个类,两个都有相同的属性名称。 一类包含不同的变量: int
, strings
, bool
和DateTime
第二类仅包含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;
}
直到现在我才想到。 当然,我已经在寻找其他类似的解决方案。 在应用了一些自己的更改之后,这没有返回任何错误,但是没有将任何加密的字符串保存到persEncrypt
类中。 我从该测试得出的结论是,它正在测试特定属性的第二个类(在我的示例中为persEncrypt
中的值是否为null,但不应这样做,它应该创建该实例的新实例。变量并将其保存在对象类中,但是删除该检查给了我同样的错误。
.Zip
将PropertyInfo对象的两个列表.Zip
,它们只是在两个列表中进行迭代,并且不检查或排序任何匹配项。 根据属性出现的顺序,这可能会导致错误的行为-请考虑使用.Join
代替匹配属性名称。 string
索引属性都将使其指向这一点,然后在尝试设置它时引发异常。 string
类型的属性-使用反射时,应改用IsAssignableFrom
,以便允许继承的类型,尽管在这种情况下,这不太可能出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.