本文整理汇总了C#中Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax类的典型用法代码示例。如果您正苦于以下问题:C# ClassDeclarationSyntax类的具体用法?C# ClassDeclarationSyntax怎么用?C# ClassDeclarationSyntax使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ClassDeclarationSyntax类属于Microsoft.CodeAnalysis.CSharp.Syntax命名空间,在下文中一共展示了ClassDeclarationSyntax类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: VisitClassDeclaration
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
Classes.Add(node);
return node;
}
开发者ID:yumapos,项目名称:Yumapos-WCF-Generator,代码行数:7,代码来源:VirtualizationVisitor.cs
示例2: IsMachine
/// <summary>
/// Returns true if the given class declaration is a P# machine.
/// </summary>
/// <param name="compilation">Compilation</param>
/// <param name="classDecl">Class declaration</param>
/// <returns>Boolean</returns>
internal static bool IsMachine(CodeAnalysis.Compilation compilation,
ClassDeclarationSyntax classDecl)
{
var result = false;
if (classDecl.BaseList == null)
{
return result;
}
var model = compilation.GetSemanticModel(classDecl.SyntaxTree);
var symbol = model.GetDeclaredSymbol(classDecl);
while (true)
{
if (symbol.ToString() == typeof(Machine).FullName)
{
result = true;
break;
}
else if (symbol.BaseType != null)
{
symbol = symbol.BaseType;
continue;
}
break;
}
return result;
}
开发者ID:yonglehou,项目名称:PSharp,代码行数:36,代码来源:Querying.cs
示例3: VisitClassDeclaration
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
var value = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
if (_first)
{
var statements = new[] { string.Format(" unityContainer.RegisterType<I{0}Service, {0}ServiceClient>(new InjectionConstructor());\r\n", _edmxName), string.Format(" unityContainer.RegisterType<I{0}ClientContext, {0}ClientContext>();\r\n", _edmxName), string.Format(" ClientContextFactory<I{0}ClientContext>.Factory = () => unityContainer.Resolve<I{0}ClientContext>();\r\n", _edmxName) };
if (_addApplicationStart)
value = value.AddMembers(
SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "OnStartup")
.WithModifiers(SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.ProtectedKeyword),
SyntaxFactory.Token(SyntaxKind.OverrideKeyword)))
.AddParameterListParameters(
SyntaxFactory.Parameter(SyntaxFactory.Identifier("e")).WithType(SyntaxFactory.ParseTypeName("StartupEventArgs")))
.WithBody(SyntaxFactory.Block().AddStatements(
SyntaxFactory.ParseStatement("IUnityContainer unityContainer = new UnityContainer();"),
SyntaxFactory.ParseStatement("unityContainer.RegisterType<IMessageBoxService, MessageBoxService>();"),
SyntaxFactory.ParseStatement("DispatcherUnhandledException += (sender, ex) => { unityContainer.Resolve<IMessageBoxService>().ShowError(ex.Exception.Message);ex.Handled = true; };"),
SyntaxFactory.ParseStatement("TaskScheduler.UnobservedTaskException += (sender, ex) => { unityContainer.Resolve<IMessageBoxService>().ShowError(ex.Exception.InnerException.Message);ex.SetObserved(); };"),
SyntaxFactory.ParseStatement("InitWAQSModules(unityContainer);"),
SyntaxFactory.ParseStatement("UIThread.Dispatcher = Application.Current.Dispatcher;"),
SyntaxFactory.ParseStatement("UIThread.TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();"),
SyntaxFactory.ParseStatement(string.Format("unityContainer.Resolve<{0}>().Show();", _pageTypeName)))));
if (_addInitWAQSModules)
return value.AddMembers(
SyntaxFactory.MethodDeclaration(
SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "InitWAQSModules")
.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)))
.AddParameterListParameters(
SyntaxFactory.Parameter(SyntaxFactory.Identifier("unityContainer")).WithType(SyntaxFactory.ParseTypeName("IUnityContainer")))
.WithBody(SyntaxFactory.Block().AddStatements(
statements.Select(s => SyntaxFactory.ParseStatement(s)).ToArray())));
}
return value;
}
开发者ID:bnjMichel,项目名称:waqs,代码行数:35,代码来源:ApplicationStartupRewriter.cs
示例4: VisitClassDeclaration
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
_cancellationToken.ThrowIfCancellationRequested();
var namedTypeSymbol = _semanticModel.GetDeclaredSymbol(node, _cancellationToken);
var classAssumptions = _classAssumptions.Where(ca => ca.Class == namedTypeSymbol).ToList();
if (classAssumptions.Count == 0)
{
return base.VisitClassDeclaration(node);
}
var newClass = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
foreach (var classAssumption in classAssumptions)
{
foreach (string attributeToDelete in classAssumption.GetAttributesToDelete(_objectTheoremResult))
{
newClass = RemoveAttribute(newClass, attributeToDelete);
}
foreach (string attributeToAdd in classAssumption.GetAttributesToAdd(_objectTheoremResult))
{
newClass = EnsureAttribute(newClass, attributeToAdd);
}
}
return newClass;
}
开发者ID:RicardoNiepel,项目名称:Z3.ObjectTheorem,代码行数:29,代码来源:AttributeRewriter.cs
示例5: AddStaticKeyword
private Task<Document> AddStaticKeyword(Document document, SyntaxNode root, ClassDeclarationSyntax classDeclaration)
{
var staticKeyword = SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithAdditionalAnnotations(Formatter.Annotation);
var newDeclaration = classDeclaration.AddModifiers(staticKeyword);
var newRoot = root.ReplaceNode(classDeclaration, newDeclaration);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:7,代码来源:CA1052CSharpCodeFixProvider.cs
示例6: GetTestFixtureDetails
public TestFixtureDetails GetTestFixtureDetails(ClassDeclarationSyntax fixtureNode, ISemanticModel semanticModel)
{
var fixture = ExtractTests(fixtureNode, semanticModel);
fixture.AssemblyName = PathHelper.GetCoverageDllName(semanticModel.GetAssemblyName());
return fixture;
}
开发者ID:pzielinski86,项目名称:RuntimeTestCoverage,代码行数:7,代码来源:NUnitTestExtractor.cs
示例7: GetFactoryMethodDeclaration
private static MethodDeclarationSyntax GetFactoryMethodDeclaration(ClassDeclarationSyntax @class)
{
return
F.MethodDeclaration(
F.ParseName(@class.Identifier.Text),
F.Identifier(F.TriviaList(F.Space), @"Factory", F.TriviaList()))
.WithModifiers(F.TokenList(
F.Token(F.TriviaList(), K.PublicKeyword, F.TriviaList(F.Space)),
F.Token(F.TriviaList(), K.StaticKeyword, F.TriviaList(F.Space))))
.WithBody(
F.Block(F.SingletonList<StatementSyntax>(
F.ReturnStatement(CallConstuctor(@class))
.WithReturnKeyword(
F.Token(
F.TriviaList(
F.Whitespace(
" ")),
K.ReturnKeyword,
F.TriviaList(
F.Space)))
.WithSemicolonToken(
F.Token(
F.TriviaList(),
K.SemicolonToken,
F.TriviaList()
))
)));
}
开发者ID:ChrisSmith,项目名称:CompileInjector,代码行数:28,代码来源:CompileInjectorModule.cs
示例8: VisitClassDeclaration
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
var typesList = new List<TypeSyntax> { _baseTypeSyntax };
if (node.BaseList != null)
typesList.AddRange(node.BaseList.Types);
var types = new SeparatedSyntaxList<TypeSyntax>();
types = types.AddRange(typesList);
var identifier = SyntaxFactory.Identifier(FurnaceTypeIdentifier + _typeName);
var newNode = node.Update(
node.AttributeLists,
node.Modifiers,
node.Keyword,
identifier,
node.TypeParameterList,
SyntaxFactory.BaseList(types),
node.ConstraintClauses,
node.OpenBraceToken,
node.Members,
node.CloseBraceToken,
node.SemicolonToken).NormalizeWhitespace();
return base.VisitClassDeclaration(newNode);
}
开发者ID:laurentkempe,项目名称:Furnace,代码行数:27,代码来源:FurnaceTypeWriter.cs
示例9: AddCodeFix
private static void AddCodeFix(CodeFixContext context, SyntaxNode root,
Diagnostic diagnostic, ClassDeclarationSyntax classNode)
{
var newRoot = IsBusinessObjectSerializableMakeSerializableCodeFix.AddAttribute(
root, classNode, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SerializableName);
if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace))
{
newRoot = (newRoot as CompilationUnitSyntax).AddUsings(
SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace)));
}
if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace))
{
newRoot = (newRoot as CompilationUnitSyntax).AddUsings(
SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace)));
}
context.RegisterCodeFix(
CodeAction.Create(
IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription,
_ => Task.FromResult<Document>(context.Document.WithSyntaxRoot(newRoot))), diagnostic);
}
开发者ID:pombredanne,项目名称:csla,代码行数:25,代码来源:IsBusinessObjectSerializableMakeSerializableCodeFix.cs
示例10: CallConstuctor
private static ObjectCreationExpressionSyntax CallConstuctor(ClassDeclarationSyntax @class)
{
var typeName = F.ParseName(@class.Identifier.Text);
var args = F.ArgumentList();
var ctor = @class.DescendantNodes().OfType<ConstructorDeclarationSyntax>().FirstOrDefault();
if(ctor != null)
{
var parameters = ctor.ParameterList.DescendantNodes().OfType<ParameterSyntax>().ToList();
foreach (var parameter in parameters)
{
var ident = parameter.DescendantNodes().OfType<IdentifierNameSyntax>().Single();
var parameterType = ident.Identifier.Text;
var invocation = F.InvocationExpression(F.MemberAccessExpression(
K.SimpleMemberAccessExpression,
F.IdentifierName(parameterType),
F.IdentifierName("Factory")));
args = args.AddArguments(F.Argument(invocation));
}
}
return F.ObjectCreationExpression(typeName)
.WithNewKeyword(F.Token(F.TriviaList(), K.NewKeyword, F.TriviaList(F.Space)))
.WithArgumentList(args);
}
开发者ID:ChrisSmith,项目名称:CompileInjector,代码行数:29,代码来源:CompileInjectorModule.cs
示例11: AddCodeFixWithNewPublicConstructor
private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root,
Diagnostic diagnostic, ClassDeclarationSyntax classNode)
{
// Generated from http://roslynquoter.azurewebsites.net/
var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier)
.WithModifiers(
SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.WithParameterList(SyntaxFactory.ParameterList()
.WithOpenParenToken(
SyntaxFactory.Token(SyntaxKind.OpenParenToken))
.WithCloseParenToken(
SyntaxFactory.Token(
SyntaxKind.CloseParenToken)))
.WithBody(SyntaxFactory.Block()
.WithOpenBraceToken(
SyntaxFactory.Token(
SyntaxKind.OpenBraceToken))
.WithCloseBraceToken(
SyntaxFactory.Token(
SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation);
var newClassNode = classNode.AddMembers(constructor);
var newRoot = root.ReplaceNode(classNode, newClassNode);
context.RegisterCodeFix(
CodeAction.Create(
CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription,
_ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),
CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic);
}
开发者ID:JorgeArellano,项目名称:csla,代码行数:30,代码来源:CheckConstructorsAnalyzerPublicConstructorCodeFix.cs
示例12: AddField
public static ClassDeclarationSyntax AddField(ClassDeclarationSyntax classDeclaration, string type, string name)
{
return classDeclaration.AddMembers(
SF.FieldDeclaration(SF.VariableDeclaration(SF.ParseTypeName(type),
SF.SeparatedList(new[] { SF.VariableDeclarator(SF.Identifier(name)) })))
.AddModifiers(SF.Token(SyntaxKind.PrivateKeyword)));
}
开发者ID:cdsalmons,项目名称:OrleansTemplates,代码行数:7,代码来源:RoslynUtils.cs
示例13: VisitClassDeclaration
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
TypeName = node.Identifier.ValueText;
TypeSyntax clientContextInterface = SyntaxFactory.ParseTypeName(string.Format("I{0}ClientContext", _edmxName));
var value = node.AddMembers(
SyntaxFactory.FieldDeclaration(
attributeLists: default(SyntaxList<AttributeListSyntax>),
modifiers: SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PrivateKeyword)),
declaration: SyntaxFactory.VariableDeclaration(
clientContextInterface,
SyntaxFactory.SeparatedList(
new[] { SyntaxFactory.VariableDeclarator(
SyntaxFactory.Identifier("_context")) }))),
SyntaxFactory.ConstructorDeclaration(SyntaxFactory.Identifier(node.Identifier.ValueText))
.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("context")).WithType(clientContextInterface))
.WithInitializer(SyntaxFactory.ConstructorInitializer(
kind: SyntaxKind.BaseConstructorInitializer,
argumentList: SyntaxFactory.ArgumentList(
arguments: SyntaxFactory.SeparatedList(
new[] { SyntaxFactory.Argument(
expression: SyntaxFactory.IdentifierName("context")) })))
.WithThisOrBaseKeyword(SyntaxFactory.Token(SyntaxKind.BaseKeyword)))
.WithBody(SyntaxFactory.Block(SyntaxFactory.ParseStatement("_context = context;"))))
.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("ViewModelBase")));
if (!value.Modifiers.Any(m => m.Kind() == SyntaxKind.PublicKeyword || m.Kind() == SyntaxKind.InternalKeyword))
value = value.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
return value;
}
开发者ID:bnjMichel,项目名称:waqs,代码行数:31,代码来源:ViewModelRewriter.cs
示例14: LookForAggregates
private void LookForAggregates(ClassDeclarationSyntax classNode)
{
if (classNode.Modifiers.Any(SyntaxKind.AbstractKeyword) || classNode.BaseList == null || !classNode.BaseList.Types.Any()) return;
// Dong Xie: Need review:
if (classNode.BaseList.Types.Any<TypeSyntax>(x => AggregateRootPlainIfx.Contains(x.ToString()))) AggregateRoots.Add(classNode);
}
开发者ID:jjrdk,项目名称:CqrsMessagingTools,代码行数:7,代码来源:MilSyntaxWalker.cs
示例15: VisitClassDeclaration
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
if (node.Modifiers.Any(m => m.Kind() == SyntaxKind.PartialKeyword))
return base.VisitClassDeclaration(node);
_notPartialClass = true;
return ((ClassDeclarationSyntax)base.VisitClassDeclaration(node)).WithModifiers(SyntaxFactory.TokenList(node.Modifiers.Union(new[] { SyntaxFactory.Token(SyntaxKind.PartialKeyword) })));
}
开发者ID:bnjMichel,项目名称:waqs,代码行数:7,代码来源:ApplicationStartRewriter.cs
示例16: checkAttribute
public static Boolean checkAttribute(IEnumerable<MethodDeclarationSyntax> methods, String attr, ClassDeclarationSyntax c)
{
Boolean isSet = false;
//Check at class level, digging two levels deep for class-level attributes in ClassDeclarationSyntax Type
foreach (var attribute in c.AttributeLists)
{
foreach (var name in attribute.Attributes)
{
if (name.Name.ToString().Equals(attr))
{
isSet = true;
}
}
}
/* If not found at Class level, check the methods
* Unfortunately MethodDeclarationSyntax is of Type IEnumerable, so we dig three levels for the Atttribute Lists
*/
foreach (var methodList in methods)
{
foreach (var methodLevelAttirbutes in methodList.AttributeLists)
{
foreach (var methodAttr in methodLevelAttirbutes.Attributes)
{
if (methodAttr.ToString().Equals(attr))
{
isSet = true;
}
}
}
}
return isSet;
}
开发者ID:hxp2k6,项目名称:DotNET-MVC-Enumerator,代码行数:32,代码来源:CheckAttribute.cs
示例17: GetUsingNamespaces
public static IEnumerable<string> GetUsingNamespaces(ClassDeclarationSyntax classes)
{
var syntaxTree = classes.SyntaxTree;
var root = (CompilationUnitSyntax)syntaxTree.GetRoot();
return root.Usings.Select(x => x.Name.ToString());
}
开发者ID:yumapos,项目名称:Yumapos-WCF-Generator,代码行数:7,代码来源:TextSerializationHelper.cs
示例18: RebuildClassAsync
private async Task<Document> RebuildClassAsync(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
{
var newImplementation = @"
private bool _isEnabled;
private readonly Action _handler;
public RelayCommand(Action handler)
{
_handler = handler;
}
public event EventHandler CanExecuteChanged;
public bool IsEnabled {
get { return _isEnabled; }
set {
if ((value != _isEnabled)) {
_isEnabled = value;
if (CanExecuteChanged != null) {
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
public bool CanExecute(object parameter)
{
return IsEnabled;
}
public void Execute(object parameter)
{
_handler();
}
";
var newClassTree = SyntaxFactory.ParseSyntaxTree(newImplementation).
GetRoot().DescendantNodes().
Where(n => n.IsKind(SyntaxKind.FieldDeclaration) || n.IsKind(SyntaxKind.MethodDeclaration) || n.IsKind(SyntaxKind.PropertyDeclaration)
|| n.IsKind(SyntaxKind.ConstructorDeclaration) || n.IsKind(SyntaxKind.EventDeclaration) || n.IsKind(SyntaxKind.EventFieldDeclaration)).
Cast<MemberDeclarationSyntax>().
Select(decl => decl.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation)).
ToArray();
ClassDeclarationSyntax newClassBlock = SyntaxFactory.ClassDeclaration("RelayCommand").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T")).WithOpenBraceToken(SyntaxFactory.ParseToken("{")).
WithCloseBraceToken(SyntaxFactory.ParseToken("}").WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed));
newClassBlock = newClassBlock.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("ICommand")));
var newClassNode = newClassBlock.AddMembers(newClassTree);
var root = await document.GetSyntaxRootAsync();
var newRoot = root.ReplaceNode(classDeclaration, newClassNode);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;
}
开发者ID:DualBrain,项目名称:DotNetAnalyzers,代码行数:60,代码来源:MakeRelayCommandRefactoring.cs
示例19: VisitClassDeclaration
public override void VisitClassDeclaration(ClassDeclarationSyntax node)
{
if (node.ShouldBeHidden()) return;
++ClassDepth;
if (ClassDepth == 1)
{
base.VisitClassDeclaration(node);
}
else if (node.ChildNodes().All(childNode => childNode is PropertyDeclarationSyntax || childNode is AttributeListSyntax))
{
// simple nested POCO
var line = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
var walker = new CodeWithDocumentationWalker(ClassDepth - 2, line);
walker.Visit(node);
this.Blocks.AddRange(walker.Blocks);
}
else
{
var methods = node.ChildNodes().OfType<MethodDeclarationSyntax>();
if (!methods.Any(m => m.AttributeLists.SelectMany(a => a.Attributes).Any()))
{
// nested class with methods that are not unit or integration tests e.g. example PropertyVisitor in Automap.doc.cs
var line = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
var walker = new CodeWithDocumentationWalker(ClassDepth - 2, line);
walker.Visit(node);
this.Blocks.AddRange(walker.Blocks);
}
}
--ClassDepth;
}
开发者ID:niemyjski,项目名称:elasticsearch-net,代码行数:31,代码来源:DocumentationFileWalker.cs
示例20: VisitClassDeclaration
/// <summary>
/// creates a new class declaration where members are delegated to the mixin
/// reference
/// </summary>
/// <param name="classDeclaration"></param>
/// <returns></returns>
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax classDeclaration)
{
var mixinName = _mixin.Name;
// currently, only three types of member forwardings are possible,
// there is a strategy for every forwarding implementation
var implementationStrategies = CreateStrategies(_mixin, _semantic, _settings);
// needed to evaluate whether type names can be reduced (depends on the using statements in the file)
var positionOfClassInSourceFile = classDeclaration.GetLocation().SourceSpan.Start;
// generate the members that should be implemented
var membersToAdd = _members
.Select(x => implementationStrategies[x.GetType()].ImplementMember(x, positionOfClassInSourceFile))
.Where(x => x != null).ToArray();
// add regions if there is something to generate
if (_settings.CreateRegions)
{
var regionCaption = $" mixin {mixinName}";
// if there is already a region, add members to this one,
// otherwise create a new one
if (classDeclaration.HasRegion(regionCaption))
return classDeclaration.AddMembersIntoRegion(regionCaption, membersToAdd);
else
membersToAdd.AddRegionAround(regionCaption);
}
// return a new class node with the additional members
// problem with AddMembers is that it adds the new code
// after the last syntax node, so when a region exists in the class
// the code will be added before the region end, this leads to the bug
// https://github.com/pgenfer/mixinSharp/issues/9
// where the newly created region is nested into the old one.
// a solution is to ensure that the members are added after any endregion directive
// check if there is an end region in the file
var lastEndRegion = classDeclaration.GetLastElementInClass<EndRegionDirectiveTriviaSyntax>();
// only interesting if there is an end region directive at all
if(lastEndRegion != null)
{
var lastSyntaxNode = classDeclaration.GetLastElementInClass<SyntaxNode>(false);
if (lastSyntaxNode != lastEndRegion && lastSyntaxNode.SpanStart < lastEndRegion.Span.End)
{
// special case here: there is an end region directive at the end of the class
// so we must add our members AFTER this endregion (by removing it and adding it before the first member)
if (membersToAdd.Length > 0)
{
var newClassDeclaration = classDeclaration.RemoveNode(lastEndRegion, SyntaxRemoveOptions.AddElasticMarker);
membersToAdd[0] = membersToAdd[0].WithLeadingTrivia(
new SyntaxTriviaList()
.Add(Trivia(EndRegionDirectiveTrivia(true)))
.Add(EndOfLine(NewLine))
.AddRange(membersToAdd[0].GetLeadingTrivia()));
return newClassDeclaration.AddMembers(membersToAdd);
}
}
}
return classDeclaration.AddMembers(membersToAdd);
}
开发者ID:pgenfer,项目名称:mixinSharp,代码行数:65,代码来源:IncludeMixinSyntaxWriter.cs
注:本文中的Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论