【问题标题】:The following throws 'is a Method but treated like a type'以下抛出“是一种方法,但被视为一种类型”
【发布时间】:2026-02-19 10:35:01
【问题描述】:

我在 ASP 中见过的最令人困惑的错误。我以前做过这样的方法调用,在我的代码的其他地方没有问题。

首先是类:

namespace LocApp.Helpers.Classes.LocationHelper
{
    public class QueryHelper
    {
        private LocAppContext db = new LocAppContext();

        public static IEnumerable<Service> getAllService()
        {
            using (var db = new LocAppContext())
            {
                var service = db.Locations.Include(s => s.LocationAssignment);

                var serv = (from s in db.Services
                            where s.active == true
                            select s).ToList();
                return serv;
            }
        }
    }
}

很容易理解发生了什么。所以让我们调用方法:

IEnumerable<LocApp.Models.Service> Service = new LocApp.Helpers.Classes.LocationHelper.QueryHelper.getAllService(Model.id);

getAllServices(Model.id) 抛出错误“是一种方法,但被视为一种类型”,嗯,不,它不能被视为一种类型......

怎么了?

【问题讨论】:

  • getAllService() 没有任何输入参数,但您正在尝试将id 传递给此方法
  • 供将来参考:您应该发布您遇到的确切错误,并且您可能想要区分 编译 错误和 运行时 人们的错误。 (这里不编译)。您可以根据是否可以运行它来区分差异。 (记住“构建和运行”是两个独立的步骤)

标签: c# asp.net-mvc-3 entity-framework


【解决方案1】:

嗯,正如错误消息所说的那样。 getAllService() 是一个方法:

public static IEnumerable<Service> getAllService()

但是你试图把它当作一个带有构造函数的类型来使用:

Service = new LocApp.Helpers.Classes.LocationHelper.QueryHelper.getAllService(...)

new 部分是这里的错误。你不想调用构造函数,你只想调用一个方法。这是一个静态方法,所以你不需要实例 - 你可以使用:

Service = LocApp.Helpers.Classes.LocationHelper.QueryHelper.getAllService(...)

请注意,如果您有适当的 using 指令,遵循 .NET 命名约定并注意单数/复数名称,您的代码将更易于遵循:

var services = QueryHelper.GetAllServices(...);

【讨论】:

    【解决方案2】:

    你的意思不是简单的:

    IEnumerable<LocApp.Models.Service> Service = LocApp.Helpers.Classes.LocationHelper.QueryHelper.getAllService();
    

    基本上去掉 new 位,并且该方法也不接受任何参数 - 我假设您在删除 new 位后会遇到这个问题。

    【讨论】:

      【解决方案3】:

      您的 getAllService 方法不带任何参数,因此您应该在不带参数的情况下调用它。它也是一个静态方法,所以不要使用new 关键字:

      IEnumerable<LocApp.Models.Service> Service = LocApp.Helpers.Classes.LocationHelper.QueryHelper.getAllService();
      

      【讨论】:

        最近更新 更多