vendredi 27 mai 2016

Reflection C# get object from static property and set an instance property

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





Aucun commentaire:

Enregistrer un commentaire