我不明白为什么GetMethod
回来null
- 两次在method1
和method
Type model = AssemblyHelper.GetTypeByClassName(Assembly.GetExecutingAssembly(), modelName + MappingColums.Tokens.Validation); // MappingColums.Tokens.Validation = "Validation"
出于测试目的,我尝试了两次 get 方法:
MethodInfo method1 = model.GetType().GetMethod(MappingColums.Tokens.Get + modelName); // MappingColums.Tokens.Get + modelName = "Get" + "Product"
MethodInfo method = model.GetType().GetMethods().FirstOrDefault(x => x.Name == MappingColums.Tokens.Get + modelName && x.GetParameters().Count() == 0);
object result = method.Invoke(model, null);
下面是我想通过反射使用的类和方法。
public class ProductValidation
{
private IProductRepository repositoryProduct;
public ProductValidation(IProductRepository repoProduct)
{
repositoryProduct = repoProduct;
}
public ICollection<Product> GetProduct()
{
return repositoryProduct.Products.ToList();
}
}
我不知道这是否重要,但我正在使用ASP.NET Core MVC
. 我Type model
在后面调试的AssemblyHelper.GetTypeByClassName
地方是Declared Methods: {System.Collections.Generic.ICollection1[AureliaCMS.Models.Entities.Product] GetProduct()}
请给我建议在哪里查找问题。
编辑:非常感谢 - 你们都是对的 -Klaus Gütter
而且Aldert
工作代码
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();
}
}
Type model = AssemblyHelper.GetTypeByClassName(Assembly.GetExecutingAssembly(), MappingColums.Tokens.EF + modelName + MappingColums.Tokens.Repository);
MethodInfo method = model.GetMethods().FirstOrDefault(x => x.Name == MappingColums.Tokens.Get + modelName + MappingColums.Tokens.Validation && x.GetParameters().Count() == 0);
ConstructorInfo constructor = model.GetConstructor(new[] { typeof(AureliaCMSStoreContext) });
object instanceConstructor = constructor.Invoke(new object[] { context });
object instanceMethod = method.Invoke(instanceConstructor, null);
你的代码永远不会工作。您需要一个对象实例来执行该方法。就像是:
Type model = AssemblyHelper.GetTypeByClassName(Assembly.GetExecutingAssembly(), modelName + MappingColums.Tokens.Validation);
MethodInfo method = model.GetMethod(MappingColums.Tokens.Get + modelName);
myClass myObject = new myObject();
object result = method.Invoke(myObject , null);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句