c# - Inferred 命名空间中的类有效,但在显式命名时无效

标签 c# generics interface

我想使用的类是 System.Web.Mvc.DependencyResolver。以下作品:

using System.Web.Mvc;
...
var x = DependencyResolver.Current.GetService<myType>();

但是,以下内容不会:

//using System.Web.Mvc;
var x = System.Web.Mvc.DependencyResolver.Current.GetService<myType>();

错误是:

The non-generic method 'IDependencyResolver.GetService(Type)' cannot be used with type arguments.

在没有 using System.Web.Mvc 指令的情况下使用什么语法。

我想要使用System.Web.Http。这两个 namespace 中都存在一些属性(RouteRoutePrefix)。 System.Web.Http 在此特定代码文件中的使用率要高得多。

最佳答案

泛型方法版本GetService<T>()是在静态类中声明的扩展方法 DependencyResolverExtensionsSystem.Web.Mvc命名空间。

这与 IDependencyResolver.GetService() 不同它被声明为 DependencyResolver 的非泛型实例方法.

由于您没有导入该命名空间,编译器无法找到实现通用扩展方法的静态类GetService<T>(this IDependencyResolver ...) .

正如 Widi 评论的那样,在没有 using 的情况下使用它您需要这样调用它的声明:

var x = System.Web.Mvc.DependencyResolverExtensions.GetService<myType>(System.Web.Mvc.D‌​ependencyResolver.Current);

关于c# - Inferred 命名空间中的类有效,但在显式命名时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37630968/

相关文章:

java - 当父类(super class)未实现接口(interface)但子类实现时,在接口(interface)子类和父类(super class)之间进行转换

java - 接口(interface)中的通用方法返回未检查的强制转换

c# - 将泛型类型声明为接口(interface)的属性?

c++ - 如何传递带有泛型参数作为参数的 lambda 函数?

c# - 如何在csharp中使用泛型类型继承

java - Spring如何过滤ApplicationEvents

c++ - 如何在 C++ 中使用代理类执行 "opt-in"接口(interface)?

c# - 将文件从控制台应用程序上传到 WebAPI

c# - 如果 ID 匹配,如何合并数据表但合并行?

c# - 方法 : params string[] with one parameter and single string