0

Many examples such as

Set object property using reflection

Instantiate an object without reflection and then use it with reflection.

But how can the same thing be achieved with reflection to get the initial object?

My code so far is this

            var currentMethod = MethodBase.GetCurrentMethod();          
            string currentNamespace = currentMethod.DeclaringType.Namespace;
            string currentType = this.GetType().Name;
            var basetype = this.GetType().Assembly.GetType(currentNamespace + "." + currentType);
            PropertyInfo propertyInfo = basetype.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static);            
            PropertyInfo propertyToSet = basetype.GetProperty(OutputVariableName, BindingFlags.Public | BindingFlags.Instance); 
            var val = propertyInfo.GetValue(propertyToSet, null);
            propertyToSet.SetValue(propertyInfo, Convert.ChangeType(prefix + suffix, propertyToSet.PropertyType), null);

This gives the error Object does not match the target type

I've also tried

            propertyInfo.SetValue(propertyToSet, Convert.ChangeType(prefix + suffix, propertyToSet.PropertyType), null);

Which gives the error Property set method not found.

The properties look like this:

    public static currentType Instance
    {
        get { return instance; }
    }

    public string NewTextName
    {
        get { return _NewTextName; }
        set { _NewTextName = value; }
    }

The intellisense for val shows all the properties and their current values, I'm expecting it to show just the property that has the name propertyToSet

The purpose of this code is to set a string property on an instance of an object. The static property returns the instance and the goal is to set the value of NewTextName, which is a non-static property.

Community
  • 1
  • 1
Adam
  • 1,825
  • 1
  • 17
  • 24
  • 1
    `Object does not match the target type` did you look at the offending line? Did you check whether all types are what you expect? – usr May 27 '16 at 13:24
  • I can't see enough information to answer that. propertyInfo and propertyToSet both appear to be correct, but they have more information in the intellisense than I would expect. – Adam May 28 '16 at 02:43

0 Answers0