2013-08-18 12 views
11

मेरे पास यह कामकाजी कोड है जो Roslyn SyntaxTree क्लास में .cs फ़ाइल लोड करेगा, एक नया PropertyDeclarationSyntax बनाएं, इसे इसमें डालें कक्षा, और .cs फ़ाइल फिर से लिखें। मैं इसे एक सीखने के अनुभव के साथ-साथ कुछ संभावित भावी विचारों के रूप में कर रहा हूं। मैंने पाया कि वास्तव में कहीं भी पूर्ण Roslyn API प्रलेखन प्रतीत नहीं होता है और मुझे यकीन नहीं है कि मैं इसे कुशलता से कर रहा हूं। मेरी मुख्य चिंता यह है कि मैं 'root.ToFullString()' कहता हूं - जब तक यह काम करता है, क्या यह सही तरीका है?सी # रोज़लिन एपीआई, एक .cs फ़ाइल पढ़ना, कक्षा को अपडेट करना, .cs फ़ाइल पर वापस लिखना

using System.IO; 
using System.Linq; 
using Roslyn.Compilers; 
using Roslyn.Compilers.CSharp; 

class RoslynWrite 
{ 
    public RoslynWrite() 
    { 
     const string csFile = "MyClass.cs"; 

     // Parse .cs file using Roslyn SyntaxTree 
     var syntaxTree = SyntaxTree.ParseFile(csFile); 
     var root = syntaxTree.GetRoot(); 
     // Get the first class from the syntax tree 
     var myClass = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); 

     // Create a new property : 'public bool MyProperty { get; set; }' 
     var myProperty = Syntax.PropertyDeclaration(Syntax.ParseTypeName("bool"), "MyProperty") 
          .WithModifiers(Syntax.Token(SyntaxKind.PublicKeyword)) 
          .WithAccessorList(
          Syntax.AccessorList(Syntax.List(
           Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) 
            .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)), 
           Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) 
            .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken))))); 

     // Add the new property to the class 
     var updatedClass = myClass.AddMembers(myProperty); 
     // Update the SyntaxTree and normalize whitespace 
     var updatedRoot = root.ReplaceNode(myClass, updatedClass).NormalizeWhitespace(); 

     // Is this the way to write the syntax tree? ToFullString? 
     File.WriteAllText(csFile, updatedRoot.ToFullString()); 
    } 
} 
+1

आप 'ToFullString() 'के बारे में क्यों चिंतित हैं? – svick

+0

मुझे कक्षा के लिए कोई दस्तावेज नहीं मिल रहा है और मुझे यकीन नहीं है कि यह सिंटैक्स पेड़ के स्ट्रिंग प्रस्तुति को निकालने और सीएस फ़ाइल को दोबारा आउटपुट करने का सबसे अच्छा तरीका है। मुझे चिंता है कि कलाकृतियों और अन्य ऐसी चीजें हो सकती हैं जो कोड पीढ़ी के लिए उपयुक्त नहीं हैं। – ShaunO

उत्तर

3

रोसलिन सीटीपी मंच in this post पर उत्तर दिया:

यही दृष्टिकोण है, आम तौर पर ठीक है, हालांकि अगर आप पूरी फ़ाइल के पाठ के लिए एक स्ट्रिंग के आवंटन को लेकर चिंतित हैं, तो आप शायद iText का उपयोग करना चाहिए। ToFullString() के बजाय लिखें (TextWriter)।

ध्यान रखें कि पेड़ों को उत्पन्न करना संभव है जो पार्सर के माध्यम से गोल-यात्रा नहीं करेंगे। उदाहरण के लिए, यदि आपने कुछ ऐसा उत्पन्न किया जो प्राथमिकता नियमों का उल्लंघन करता है, तो सिंटैक्सट्री निर्माण API इसे पकड़ नहीं पाएंगे।

+0

उत्तर के लिए धन्यवाद; मैंने सोचा कि कुछ और एपीआई विशिष्ट मंच होना चाहिए! – ShaunO

संबंधित मुद्दे