How does Roslyn implement simple code prompts?
If you need to implement a code editor, one of the most important functions is to implement code prompts, similar to the Code smart prompts of. The following describes how to use the Roslyn compiler to implement a simple code prompt function.
The Code prompts that you must first know the object type information and then obtain members through iteration.
1 static void Main (string [] args) 2 {3 4 var code = @ "5 using System; 6 public class _ RoslynCodeCompletionSample 7 {8 public void MyMethod () 9 {10 var datetime = DateTime. now; 11 datetime.12} 13} "; 14 // Microsoft. codeAnalysis. CSharp namespace15 var syntaxTree = CSharpSyntaxTree. parseText (code); 16 // introduce the Assembly 17 var cscompilation = CSharpCompilation required by DateTime. create ("_ RoslynCodeCompletionSample") 18. AddReferences (MetadataReference. createFromAssembly (typeof (DateTime ). assembly) 19. addSyntaxTrees (syntaxTree); 20 var semanticModel = cscompilation. getSemanticModel (syntaxTree); 21 // get the code prompt datetime. medium. textSpan object 22 string codeIndex = "datetime. "; 23 var dotTextSpan = new TextSpan (code. indexOf (codeIndex) + codeIndex. length-1, 1); 24 var memberAccessNode = (MemberAccessExpressionSyntax) syntaxTree. getRoot () 25. descendantNodes (dotTextSpan ). last (); 26 // obtain type information 27 var lhsType = semanticModel. getTypeInfo (memberAccessNode. expression ). type; 28 // get the content of the code prompt 29 foreach (var symbol in lhsType. getMembers () 30 {31 if (! Symbol. CanBeReferencedByName32 | symbol. DeclaredAccessibility! = Accessibility. Public33 | symbol. IsStatic) 34 continue; 35 36 Console. WriteLine (symbol. Name); 37} 38 Console. ReadLine (); 39}