मेरे पास यह कामकाजी कोड है जो 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());
}
}
आप 'ToFullString() 'के बारे में क्यों चिंतित हैं? – svick
मुझे कक्षा के लिए कोई दस्तावेज नहीं मिल रहा है और मुझे यकीन नहीं है कि यह सिंटैक्स पेड़ के स्ट्रिंग प्रस्तुति को निकालने और सीएस फ़ाइल को दोबारा आउटपुट करने का सबसे अच्छा तरीका है। मुझे चिंता है कि कलाकृतियों और अन्य ऐसी चीजें हो सकती हैं जो कोड पीढ़ी के लिए उपयुक्त नहीं हैं। – ShaunO