我試圖讓自己的移動到資源重構(就像ReSharper中發現的那樣)。在我CodeAction.GetChangedDocumentAsync
方法我在做這3個步驟:移動到資源重構
- 添加我的資源到Resources.resx文件,
XmlDocument
- 使用DTE運行自定義工具來更新Resources.Designer.cs文件
- 由新資源的合格標識與
SyntaxNode.ReplaceNode
步驟1 & 2都OK,但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);
什麼是'newNode'? – SLaks
'newNode'是一個'QualifiedName':Properties.Resources.MyResource – Maxence
究竟發生了什麼?但你不能這樣做;代碼操作必須是純函數。例如,懸停預覽怎麼樣? – SLaks