我正在開發一個應用程序,用於說明CSharp
代碼。我正在用Roslyn
這樣做。我面臨着splitting expressions
的問題。將表達式語句拆分爲Roslyn
Sample類
class Program
{
static void Main(string[] args)
{
float floatVariable = 20;
Int16 intVariable = 10;
string str = "School";
Console.Write(str + floatVariable.ToString() + intVariable.ToString()); // Facing problem with this statement
}
}
樣品我使用
string code = new StreamReader(classPath).ReadToEnd();
var syntaxTree = CSharpSyntaxTree.ParseText(code);
var syntaxRoot = syntaxTree.GetRoot();
//This will get the method and local variables declared inside the method
var MyMethods = syntaxRoot.DescendantNodes().OfType<MethodDeclarationSyntax>();
foreach (MethodDeclarationSyntax mds in MyMethods)
{
syntaxTree = CSharpSyntaxTree.ParseText(mds.ToFullString());
IEnumerable<SyntaxNode> nodes = syntaxTree.GetRoot().DescendantNodes();
IEnumerable<VariableDeclarationSyntax> variableDeclarations = nodes.OfType<VariableDeclarationSyntax>();
foreach (VariableDeclarationSyntax variable in variableDeclarations)
{
// I will collect the variable details like Datatype, variable names and initialized values here
}
foreach (StatementSyntax statement in mds.Body.Statements)
{
if (statement.CSharpKind() == SyntaxKind.ExpressionStatement)
{
//I want to split the expressions "Console.Write(str + floatVariable.ToString() + intVariable.ToString());" as below
//1. intVariable.ToString()
//2. floatVariable.ToString()
//3. str
//Then I have to find the whole data type from the resolved result of above 3 => string here
}
}
}
任何幫助的代碼將不勝感激。
編輯: 我有在分割參數表達式語句的麻煩。我試圖做到這一點,
if (statement.CSharpKind() == SyntaxKind.ExpressionStatement)
{
ExpressionStatementSyntax expression = statement as ExpressionStatementSyntax;
var expressions = expression.Expression.DescendantNodes();
}
但是這將每個標記拆分爲一個單獨的元素。我只是想分裂Console.Write(str + floatVariable.ToString() + intVariable.ToString())
成,
- Console.Write()
- 海峽
- intVariable.ToString()
- floatVariable.ToString()
的[羅斯林語法樹Visualiser的](https://visualstudiogallery.msdn.microsoft.com/70e184da-9b3a- 402f-b210-d62a898e2887)可能會幫助你。 – Rawling
究竟是什麼問題?從語句中獲取參數表達式?使用'+'的二進制表達式?你有什麼嘗試?它是如何失敗的? – svick
@svick:我編輯了這個問題。請在**編輯**塊中找到它。 –