vendredi 28 avril 2017

PropertyInfo.SetValue - when using in loop <--target exception

i have some problem with Reflection again... I get values from databases (strings). In loop i want to assign values to object.

first i check if class already exists if not i will create her.

                if (exists2 == null)
                {
                    newInstance = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(classFullName);
                }

                else
                {
                    newInstance = exists2;
                }

now i have access to class.

i try to assign to String type value with string

                var newInstanceClassType = Type.GetType(classFullName);
                PropertyInfo pi = newInstanceClassType.GetProperty(newInstancePropertyName);

                if (pi.PropertyType.FullName == "System.String")
                {
                    var stringNewInstance = Activator.CreateInstance(typeof(System.String), new object[] {value.ToCharArray() });
                    //pi.SetValue(stringNewInstance, value, null);
                    pi.SetValue(newInstance, Convert.ChangeType(stringNewInstance,pi.PropertyType), null);
                }

                else
                {
                    pi.SetValue(newInstance, value, null);
                }

and... the first value now is assigned to right property. (everything is ok) but in the second loop it crashes (TargetException was unhandled) Object type is not match with target type

In the loop i only check if object of some class already exists - if exists i dont want to create new object, i want to assign next value to next property

it doesnt matter what i have in both strings, when i change order in database of these strings it again crash at the second string...

any ideas what is wrong here?





Aucun commentaire:

Enregistrer un commentaire