GetMethod返回空C#

时间:2019-01-19 10:27:58

标签: c# asp.net-core reflection

我不明白为什么GetMethod返回null-在method1method两次返回

Type model = AssemblyHelper.GetTypeByClassName(Assembly.GetExecutingAssembly(), modelName + MappingColums.Tokens.Validation); // MappingColums.Tokens.Validation = "Validation"

出于测试目的,我尝试两次获取方法:

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ütterAldert

工作代码

    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);

1 个答案:

答案 0 :(得分:1)

您的代码将永远无法使用。您需要对象的实例才能在其上执行该方法。像这样:

    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);