Tomas
Tomas

Reputation: 18127

GetValue return Object does not match target type

Already spend one hour trying to solve the problem with GetValue which always return

"GetValue return Object does not match target type".

I need to read API abstract property value from child class, any suggestion how to do that?

The classes

Parent
public abstract partial class EntityBase
{
   public abstract int Api { get; }
}

Child
public sealed class Email2Pdf : EntityBase
{
  public override int Api
  {
    get { return 12; }
  }
}

The actual code which gives exception

var subClasses = typeof(EntityBase).GetSubClasses(true);
foreach (var subClass in subClasses)
{
 //I always get exception here!!!
 var value = subClass.GetProperty("Api", BindingFlags.Instance | BindingFlags.Public).GetValue(subClass, null); 
}

     public static class TypeExtensions
        {
            public static List<Type> GetSubClasses(this Type baseType, bool topMostOnly = false)
            {
                var subClasses = baseType.Assembly.GetTypes().Where(type => type.IsSubclassOf(baseType)).ToList();

                if (topMostOnly)
                {
                    subClasses.RemoveAll(subClass => subClass.IsAbstract);
                }

                return subClasses;
            }

        }

Upvotes: 0

Views: 1047

Answers (1)

Lee
Lee

Reputation: 144206

The first argument of GetValue is the object to get the property value for. You are passing an instance of the System.Type class, hence the error. You need to pass an instance of the associated type.

Assuming each subclass has a default constructor, you can create one with Activator.CreateInstance e.g.

foreach (var subClass in subClasses)
{
   var instance = (EntityBase)Activator.CreateInstance(subClass);
   var value = subClass.GetProperty("Api", BindingFlags.Instance | BindingFlags.Public).GetValue(instance, null); 
}

Upvotes: 2

Related Questions