samedi 19 mars 2016

C# Invoke generic method with casted property as parameter

I have a generic class with a generic method:

public class GenericClass<T> where T : class
{
   public void GenericMethod<T>(T item)
   {
      // do work here
   }
}

I also have an object with multiple properties, some of which can be other objects:

public class TestObject
{
   public ChildObject ChildObject { get; set; }
}

I am then attempting to use a generic method which will reflect through TestObject and call GenericMethod for all properties that are in and of themselves custom classes such as ChildObject (I do have a way of determining this based on inheritance, however for the sake of keeping it simple did not include that code for this example):

public void ReflectingMethod<T>(T item)
{
   var properties = item.GetType().GetProperties();

   foreach (var property in properties)
   {
      var type = property.PropertyType;
      var castedObject = Convert.ChangeType(property, type);
      var genericClass = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(type));
      var method = genericClass.GetType().GetMethod("GenericMethod", new [] { type });

      method.Invoke(castedObject, null);
   }
}

The problem is that whether I attempt to change property's type (as shown in the above example) or I pass property directly to method.Invoke, such as:

method.Invoke(property, null);

I still receive the same error:

Object does not match target type.

At RunTime method is:

GenericMethod(TestProject.ChildObject)

And castedObject is:

TestProject.ChildObject

I am confused as to why I am getting the error I am, when it would appear that the casted object is exactly of the type that the method is looking for.





Aucun commentaire:

Enregistrer un commentaire