This question already has an answer here:
I'm getting error during GetValue
"Object does not match target type."
My aim is to pass some strings like:
- interface names, class names, property names
for ViewComponent that could use different repositories in many views.
ViewComponent - my test code for reflection
I'm getting error here --> test1
public class DataFilterAutocompleteViewComponent : ViewComponent
{
public Assembly Assembly
{
get
{
return Assembly.GetExecutingAssembly();
}
}
public IViewComponentResult Invoke(string blablabla)
{
Type interfaceType = AssemblyHelper.GetTypeByClassName(Assembly, Interfaces.Repo.EFProductRepository).GetInterface(Interfaces.IProductRepository);
Type repoType = AssemblyHelper.GetTypeByClassName(Assembly, Interfaces.Repo.EFProductRepository);
var test = interfaceType.GetProperty("testProducts"); //.GetValue(new List<Product>())
var test1 = test.GetValue(new List<Product>());
return View(blablabla);
}
}
AssemblyHelper
public static class AssemblyHelper
{
public static IEnumerable<Type> GetLoadableTypes(Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
public static Type GetTypeByClassName(Assembly assembly, string className)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
return AssemblyHelper.GetLoadableTypes(assembly).Where(a => a.Name == className).FirstOrDefault();
}
public static string GetAssemblyName()
{
return Assembly.GetExecutingAssembly().GetName().Name;
}
public static Object GetConstructorByClassName(Assembly assembly, string className)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
if (className == null) throw new ArgumentNullException("Cant find class: " + className);
Type type = Type.GetType(AssemblyHelper.GetTypeByClassName(assembly, className) + ", " + AssemblyHelper.GetAssemblyName());
return Activator.CreateInstance(type);
}
}
Interface
public interface IProductRepository
{
IQueryable<Product> Products { get; }
List<Product> testProducts { get; }
}
Question: I don't understand why I'm getting such an error. I'm passing a correct type for this property.
Aucun commentaire:
Enregistrer un commentaire