简体   繁体   中英

Why does Reflection's SetValue throw an exception?

I am trying to copy some property values from one object to another (both objects implement IVenue, but object b needs to have some values removed dynamically). Wanting to avoid a lot of code like:

a.Property1 = b.Property1;
a.Property2 = b.Property2;
etc

I am attempting to use Reflection to loop the properties and copy across:

public VenueContract(TVDData.Interfaces.IVenue v, List<TVDData.APIClientPermittedFields> permittedFields)
{
    PropertyInfo[] Properties = this.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo p in Properties)
    {
        PropertyInfo source = v.GetType().GetProperty(p.Name, BindingFlags.Public | BindingFlags.Instance);
        p.SetValue (p, source.GetValue(v,null),null);
    }
}

However I receive the error:

"Object does not match target type"

Both properties are type int, declared as:

public int ID { get; set; }

The problem appears to lie in p.SetValue as source.GetValue(v,null) returns the expected value.

Can anyone explain what I am doing wrong? Feel free to suggest a completely alternative approach if that would be a more appropriate solution.

Your first argument on SetValue is incorrect - it's try to set the property on the PropertyInfo .

You probably meant:

 p.SetValue(this, source.GetValue(v, null), null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM