目前,我在同一个库中有两个函数,在我的情况下都可以调用它们。如何指定函数的特定名称空间,以便对其进行调用。
在以下方法或属性之间的调用是不明确的:'Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.UseContentRoot(Microsoft.AspNetCore.Hosting.IWebHostBuilder,string)'
和
'Microsoft.AspNetCore.Hosting.HostingAbstractionsWebHostBuilderExtensions.UseContentRoot(Microsoft.AspNetCore.Hosting.IWebHostBuilder,字符串)'
那是错误(阅读起来有点混乱),但这就是问题所在。
这是代码:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) //The Problem!!
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
最佳答案
您使用的是流畅的表示法(对链接在一起的方法的成功调用),并且在此过程中依赖于静态扩展方法,所有这些都是不错的样式。不确定如何保留这种漂亮的样式,但是如果将其拆开,则可以通过名称空间来定位所需的方法调用。
var intermediateResult = new WebHostBuilder()
.UseKestrel();
现在选择所需的方法(我的示例使用第一个名称空间中的方法,但这是您的选择)。
Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.UseContentRoot(intermediateResult, Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
丑陋,但它应该可以编译并且可以运行。
注意。您会注意到,我使用两个参数调用了方法
UseContentRoot()
!那只是在说明下面的情况。静态扩展方法用表示该类将用作扩展方法的类的初始参数编写。因此,实际上
UseContentRoot(String currentDir)
的写法类似于UseContentRoot(this IWebHostBuilder builder, String currentDir)
,这意味着UseContentRoot
是为类(接口)IWebHostBuilder
编写的扩展方法。现在,特殊的
this
关键字用法允许该方法被调用(并链接到您的情况),就像该方法是IWebHostBuilder的成员一样,因此,如果您有IWebHostBuilder builder
,则可以执行builder.UseContentRoot(currentDir)
。因此,初始参数“移动”到点的左侧,看起来此扩展方法在IWebHostBuilder
上声明为采用一个参数的方法。但是调用它好像它是属于
IWebHostBuilder
的方法一样,只是一种方便。您仍然可以使用最初声明的方法来调用该方法,同时具有两个声明的参数:UseContentRoot(IWebHostBuilder builder, String currentDir)
,这是实际声明的方式。关于c# - 如何在C#中调用特定 namespace 的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38906183/