How does Roslyn implement simple code prompts?

Source: Internet
Author: User

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}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.