我在YouTube上观看了有关入门的视频后,尝试对Visual Studio进行扩展。按照一些说明进行操作后,在尝试在工具下的菜单中为自定义命令设置扩展名时遇到了一个小错误。
DTE2 dte = (DTE2)ServiceProvider.GetServiceAsync(typeof(DTE));
我的ServiceProvider是IAsyncServiceProvider
而不是ServiceProvider
。因此,有一种方法可以使DTE2对象完全从IAsyncServiceProvider
更改为ServiceProvider
。
我的代码:
<code> public static async Task InitializeAsync(AsyncPackage package)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
OleMenuCommandService commandService = await package.GetServiceAsync((typeof(IMenuCommandService))) as OleMenuCommandService;
Instance = new FRC(package, commandService);
}
public static void ExecuteCommand(DTE2 dte, string commandName)
{
ThreadHelper.ThrowIfNotOnUIThread();
var command = dte.Commands.Item(commandName);
if (command.IsAvailable)
{
dte.ExecuteCommand(command.Name);
}
}
private void Execute(object sender, EventArgs e)
{
DTE2 dte = package.GetServiceAsync(typeof(DTE2)) as DTE2;
ThreadHelper.ThrowIfNotOnUIThread();
ExecuteCommand(dte, string.Format("View.ClassView"));
}
}
</code>
他的代码:
var dte = (DTE2)ServiceProvider.GetService(typeof(DTE));
答案 0 :(得分:1)
您正在谈论的视频:https://www.youtube.com/watch?v=MFiRotBsVKU
我使用了Andre.L解决方案及其工作方式。
代码及其功能中有两行更改
private void Execute(object sender, EventArgs e)
首先通过将关键字async
添加到函数签名中
private async void Execute(object sender, EventArgs e)
然后通过更改此行
DTE2 dte = package.GetServiceAsync(typeof(DTE2)) as DTE2;
进入此
var dte = await package.GetServiceAsync(typeof(DTE)).ConfigureAwait(false) as DTE2;
答案 1 :(得分:0)
这是一个异步函数,请尝试以下方法:
private async void Execute(object sender, EventArgs e)
{
var dte = await package.GetServiceAsync(typeof(DTE));
DTE2 dte2 = dte2 as DTE2;
if(dte2 != null){
ExecuteCommand(dte2, string.Format("View.ClassView"));
}
}
或者,通过ConfigureAwait:
private async void Execute(object sender, EventArgs e)
{
DTE2 dte2 = await package.GetServiceAsync(typeof(DTE)).ConfigureAwait(false) as DTE2;
if(dte2 != null){
ExecuteCommand(dte2, string.Format("View.ClassView"));
}
}