简体   繁体   中英

SetValue Method throw Exception when using reflection

I'm trying to set value to properties in many objects. I've a function that receive 2 parameters MyStructuredObjects and MyObject MyStructuredObjects has a list of MyObjects. This Function is a re-factory to remove a lot of 'if's.

I'd like to use ever the same object because the function it is used in a loop.If it is possible. I've getting ever the exception 'Object does not match target'. Sorry posting this, but I don't found problems like this, using List inside a Object structure.

Take a look :

public class MyStructuredObjects
{
    public List<MyObject1> Object1 { get; set; }
    public List<MyObject2> Object2 { get; set; }
    public List<MyObject3> Object3 { get; set; }
    public List<MyObject4> Object4 { get; set; }
    public List<MyObject5> Object5 { get; set; }
}

private void SetValuesToObjectsToIntegrate<T>(ref MyStructuredObjects returnedObject, T obj)
{
    Type t = obj.GetType();
    var propertyInfo = new ObjectsToIntegrate().GetType().GetProperties();
    var instance = Activator.CreateInstance(t);
    foreach (var item in returnedObject.GetType().GetProperties())
    {
        var itemType = item.PropertyType;
        if (t == itemType)      // PASSING BY HERE OK , it finds the same type :P
        {
            item.SetValue(t, Convert.ChangeType(obj, item.PropertyType), null);
        }
    }
}

Update: The code should be:

item.SetValue(instance, Convert.ChangeType(obj, item.PropertyType), null);

I think I understand what you're trying to do.

It appears that you're trying to set properties like this:

var o2 = new List<MyObject2>();
var mso = new MyStructuredObjects();
SetValuesToObjectsToIntegrate(ref mso, o2);

So that mso will have its property Object2 set because the type of o2 matches the property type.

If that's the case, then you only need this code:

private void SetValuesToObjectsToIntegrate<T>(MyStructuredObjects returnedObject, T obj)
{
    foreach (var propertyInfo in typeof(MyStructuredObjects).GetProperties())
    {
        if (typeof(T) == propertyInfo.PropertyType)
        {
            propertyInfo.SetValue(returnedObject, obj, null);
        }
    }
}

There's no need to pass MyStructuredObjects returnedObject by ref as you're not changing the instance of returnedObject .

Use this to call this code:

var o2 = new List<MyObject2>();
var mso = new MyStructuredObjects();
SetValuesToObjectsToIntegrate(mso, o2);

After this call I now get:

结果

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