c# - 转向资源重构

标签 c# visual-studio roslyn resx vsix

我正在尝试进行我自己的移动到资源 重构(就像在 ReSharper 中找到的那样)。在我的 CodeAction.GetChangedDocumentAsync 方法中,我执行以下 3 个步骤:

  1. 使用 XmlDocument 将我的资源添加到 Resources.resx 文件中
  2. 使用DTE运行自定义工具更新Resources.Designer.cs文件
  3. SyntaxNode.ReplaceNode 的新资源的限定标识符替换文字字符串

第 1 步和第 2 步都可以,但第 3 步不起作用。如果我删除第 2 步,则第 3 步会起作用。

我不知道是因为我在混合使用 Roslyn 和 DTE,还是因为第 2 步在解决方案中生成了新代码并且我的缓存上下文变得无效。

// Add the resource to the Resources.resx file
var xmlDoc = new XmlDocument();
xmlDoc.Load(resxPath);
XmlNode node = xmlDoc.SelectSingleNode($"//data[@name='{resourceIndentifierName}']");
if (node != null) return;
XmlElement dataElement = xmlDoc.CreateElement("data");

XmlAttribute nameAtt = xmlDoc.CreateAttribute("name");
nameAtt.Value = resourceIndentifierName;
dataElement.Attributes.Append(nameAtt);

XmlAttribute spaceAtt = xmlDoc.CreateAttribute("space", "xml");
spaceAtt.Value = "preserve";
dataElement.Attributes.Append(spaceAtt);

XmlElement valueElement = xmlDoc.CreateElement("value");
valueElement.InnerText = value;
dataElement.AppendChild(valueElement);

XmlNode rootNode = xmlDoc.SelectSingleNode("//root");
Debug.Assert(rootNode != null, "rootNode != null");
rootNode.AppendChild(dataElement);
xmlDoc.Save(resxPath);

// Update the Resources.Designer.cs file
var dte = (DTE2)Package.GetGlobalService(typeof(SDTE));
ProjectItem item = dte.Solution.FindProjectItem(resxPath);
((VSProjectItem) item.Object)?.RunCustomTool();

// Replace the node
SyntaxNode oldRoot = await context.Document.GetSyntaxRootAsync(cancellationToken)
  .ConfigureAwait(false);
SyntaxNode newRoot = oldRoot.ReplaceNode(oldNode, newNode);
return context.Document.WithSyntaxRoot(newRoot);

最佳答案

it's because step 2 generate new code in the solution and my cached context becomes invalid

这就是正在发生的事情。当您调用 RunCustomTool 时,visual studio file watcher api 会告诉 roslyn 文件已更新并且 roslyn 会生成一组新的解决方案快照。当您尝试应用代码修复时,roslyn 查看您的代码修复来自的解决方案快照,发现它与当前快照不匹配,因此无法应用。

关于c# - 转向资源重构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682633/

相关文章:

c# - 向用户报告异常消息时的最佳实践

c# - LINQ 计算出现次数

c# - 如何在 ngrok 上部署 visual studio 项目?

visual-studio-2010 - 如果另一个测试用例未在 Microsoft 测试管理器中运行,则禁用一个测试用例

visual-studio - 用于自定义命令的 Visual Studio vsix 包,类似于 "Go To Definition"(F12)

roslyn - SyntaxRewriter 和多个语句

c# - 如何使用 Perforce 在 Visual Studio 中重命名文件时保留更改历史记录

c# - 无法获取 Web 浏览器文档的元素

Git 更改和作者未显示上述函数和属性

ASP.NET Web API 站点虚拟目录可访问,但 Controller 操作返回 HTTP 503