本文整理汇总了C#中SyntaxGenerator.ParameterDeclaration方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxGenerator.ParameterDeclaration方法的具体用法?C# SyntaxGenerator.ParameterDeclaration怎么用?C# SyntaxGenerator.ParameterDeclaration使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SyntaxGenerator
的用法示例。
在下文中一共展示了SyntaxGenerator.ParameterDeclaration方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Fix
private static async Task<Document> Fix(CodeFixContext context, SyntaxNode root, SyntaxGenerator generator, SemanticModel semanticModel, CancellationToken cancellationToken)
{
SyntaxNode node = root.FindNode(context.Span);
Diagnostic diagnostic = context.Diagnostics.First();
switch (diagnostic.Properties[OperatorOverloadsHaveNamedAlternatesAnalyzer.DiagnosticKindText])
{
case OperatorOverloadsHaveNamedAlternatesAnalyzer.AddAlternateText:
SyntaxNode methodDeclaration = generator.GetDeclaration(node, DeclarationKind.Operator) ?? generator.GetDeclaration(node, DeclarationKind.ConversionOperator);
var operatorOverloadSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken);
INamedTypeSymbol typeSymbol = operatorOverloadSymbol.ContainingType;
// For C# the following `typeDeclarationSyntax` and `typeDeclaration` nodes are identical, but for VB they're different so in
// an effort to keep this as language-agnostic as possible, the heavy-handed approach is used.
SyntaxNode typeDeclarationSyntax = typeSymbol.DeclaringSyntaxReferences.First().GetSyntax(cancellationToken);
SyntaxNode typeDeclaration = generator.GetDeclaration(typeDeclarationSyntax, DeclarationKind.Class);
SyntaxNode addedMember;
ImmutableArray<SyntaxNode> bodyStatements = ImmutableArray.Create(
generator.ThrowStatement(generator.ObjectCreationExpression(semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"))));
if (OperatorOverloadsHaveNamedAlternatesAnalyzer.IsPropertyExpected(operatorOverloadSymbol.Name))
{
// add a property
addedMember = generator.PropertyDeclaration(
name: OperatorOverloadsHaveNamedAlternatesAnalyzer.IsTrueText,
type: generator.TypeExpression(SpecialType.System_Boolean),
accessibility: Accessibility.Public,
modifiers: DeclarationModifiers.ReadOnly,
getAccessorStatements: bodyStatements);
}
else
{
// add a method
ExpectedMethodSignature expectedSignature = GetExpectedMethodSignature(operatorOverloadSymbol, semanticModel.Compilation);
addedMember = generator.MethodDeclaration(
name: expectedSignature.Name,
parameters: expectedSignature.Parameters.Select(p => generator.ParameterDeclaration(p.Item1, generator.TypeExpression(p.Item2))),
returnType: generator.TypeExpression(expectedSignature.ReturnType),
accessibility: Accessibility.Public,
modifiers: expectedSignature.IsStatic ? DeclarationModifiers.Static : DeclarationModifiers.None,
statements: bodyStatements);
}
SyntaxNode newTypeDeclaration = generator.AddMembers(typeDeclaration, addedMember);
return context.Document.WithSyntaxRoot(root.ReplaceNode(typeDeclaration, newTypeDeclaration));
case OperatorOverloadsHaveNamedAlternatesAnalyzer.FixVisibilityText:
SyntaxNode badVisibilityNode = generator.GetDeclaration(node, DeclarationKind.Method) ?? generator.GetDeclaration(node, DeclarationKind.Property);
ISymbol badVisibilitySymbol = semanticModel.GetDeclaredSymbol(badVisibilityNode, cancellationToken);
SymbolEditor symbolEditor = SymbolEditor.Create(context.Document);
ISymbol newSymbol = await symbolEditor.EditOneDeclarationAsync(badVisibilitySymbol,
(documentEditor, syntaxNode) => documentEditor.SetAccessibility(badVisibilityNode, Accessibility.Public)).ConfigureAwait(false);
Document newDocument = symbolEditor.GetChangedDocuments().Single();
SyntaxNode newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return context.Document.WithSyntaxRoot(newRoot);
default:
return context.Document;
}
}
示例2: CreateAnalysisMethod
internal static SyntaxNode CreateAnalysisMethod(SyntaxGenerator generator, string methodName, SemanticModel semanticModel)
{
var type = SyntaxFactory.ParseTypeName("SyntaxNodeAnalysisContext");
var parameters = new[] { generator.ParameterDeclaration("context", type) };
SyntaxList<SyntaxNode> statements = new SyntaxList<SyntaxNode>();
INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException");
statements = statements.Add(generator.ThrowStatement(generator.ObjectCreationExpression(notImplementedException)));
SyntaxNode newMethodDeclaration = generator.MethodDeclaration(methodName, parameters: parameters, accessibility: Accessibility.Private, statements: statements);
return newMethodDeclaration.WithLeadingTrivia(SyntaxFactory.ParseLeadingTrivia("// This method, which is the method that is registered within Initialize, performs the analysis of the Syntax Tree when an IfStatementSyntax Node is found. If the analysis finds an error, a diagnostic is reported").ElementAt(0), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.ParseLeadingTrivia("// In this tutorial, this method will walk through the Syntax Tree seen in IfSyntaxTree.jpg and determine if the if-statement being analyzed has the correct spacing").ElementAt(0), SyntaxFactory.CarriageReturnLineFeed);
}
示例3: BuildInitialize
internal static SyntaxNode BuildInitialize(SyntaxGenerator generator, INamedTypeSymbol notImplementedException, SyntaxList<StatementSyntax> statements, string name)
{
var type = SyntaxFactory.ParseTypeName("AnalysisContext");
var parameters = new[] { generator.ParameterDeclaration(name, type) };
if (notImplementedException != null)
{
statements = statements.Add(generator.ThrowStatement(generator.ObjectCreationExpression(notImplementedException)) as StatementSyntax);
}
var initializeDeclaration = generator.MethodDeclaration("Initialize", parameters: parameters, accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Override, statements: statements);
return initializeDeclaration;
}
示例4: CreateNewMethod
private static SyntaxNode CreateNewMethod(
SyntaxGenerator generator, IMethodSymbol methodSymbol, int parameterIndex, Compilation compilation, INamedTypeSymbol uriType)
{
// create original parameter decl
var originalParameter = generator.ParameterDeclaration(methodSymbol.Parameters[parameterIndex]);
// replace original parameter type to System.Uri
var newParameter = generator.ReplaceNode(originalParameter, generator.GetType(originalParameter), generator.TypeExpression(uriType));
// create original method decl
var original = generator.MethodDeclaration(methodSymbol, generator.DefaultMethodBody(compilation));
// get parameters from original method decl
var originalParameters = generator.GetParameters(original);
// replace one of parameter to new one
return generator.ReplaceNode(original, originalParameters[parameterIndex], newParameter);
}
示例5: GetPropertyDeclarationSyntax
private static SyntaxNode GetPropertyDeclarationSyntax(
SyntaxGenerator syntaxGenerator,
SemanticModel semanticModel,
IPropertySymbol propertySymbol)
{
var getAccessorStatements = GetPropertyGetAccessorsSyntax(syntaxGenerator, semanticModel, propertySymbol).ToList();
var setAccessorStatements = GetPropertySetAccessorsSyntax(syntaxGenerator, semanticModel, propertySymbol).ToList();
var declarationModifiers = DeclarationModifiers.None;
if (getAccessorStatements.Count == 0)
{
declarationModifiers = declarationModifiers.WithIsWriteOnly(true);
// set-only properties are not currently supported
return null;
}
if (setAccessorStatements.Count == 0)
{
declarationModifiers = declarationModifiers.WithIsReadOnly(true);
}
if (!propertySymbol.IsIndexer)
{
return syntaxGenerator
.PropertyDeclaration(
propertySymbol.Name,
syntaxGenerator.TypeExpression(propertySymbol.Type),
accessibility: Accessibility.Public,
modifiers: declarationModifiers,
getAccessorStatements: getAccessorStatements,
setAccessorStatements: setAccessorStatements);
}
else
{
var parameters = propertySymbol
.Parameters
.Select(x => syntaxGenerator.ParameterDeclaration(x.Name, syntaxGenerator.TypeExpression(x.Type)))
.ToList();
return syntaxGenerator
.IndexerDeclaration(
parameters,
syntaxGenerator.TypeExpression(propertySymbol.Type),
accessibility: Accessibility.Public,
modifiers: declarationModifiers,
getAccessorStatements: getAccessorStatements,
setAccessorStatements: setAccessorStatements);
}
}
示例6: CreateMethodWithContextParameter
// creates a method keeping everything except for the parameters, and inserting a parameter of type SyntaxNodeAnalysisContext
protected internal static SyntaxNode CreateMethodWithContextParameter(SyntaxGenerator generator, MethodDeclarationSyntax methodDeclaration)
{
TypeSyntax type = SyntaxFactory.ParseTypeName("SyntaxNodeAnalysisContext");
SyntaxNode[] parameters = new[] { generator.ParameterDeclaration("context", type) };
string methodName = methodDeclaration.Identifier.Text;
TypeSyntax returnType = methodDeclaration.ReturnType;
SyntaxList<StatementSyntax> statements = methodDeclaration.Body.Statements;
SyntaxNode newDeclaration = generator.MethodDeclaration(methodName, parameters, returnType: returnType, accessibility: Accessibility.Private, statements: statements);
return newDeclaration;
}
示例7: GetConstructorDeclarationSyntax
private static SyntaxNode GetConstructorDeclarationSyntax(
SyntaxGenerator syntaxGenerator,
SemanticModel semanticModel,
string name)
{
// GENERATED CODE:
//
// public Name(MockBehavior behavior = MockBehavior.Strict)
// : base(behavior)
// {
// if (behavior == MockBehavior.Loose)
// {
// ConfigureLooseBehavior();
// }
// }
var mockBehaviorType = syntaxGenerator
.TypeExpression(
semanticModel
.Compilation
.GetTypeByMetadataName("PCLMock.MockBehavior"));
return syntaxGenerator
.ConstructorDeclaration(
name,
parameters: new[]
{
syntaxGenerator
.ParameterDeclaration(
"behavior",
mockBehaviorType,
initializer: syntaxGenerator.MemberAccessExpression(mockBehaviorType, "Strict"))
},
accessibility: Accessibility.Public,
baseConstructorArguments: new[] { syntaxGenerator.IdentifierName("behavior") },
statements: new[]
{
syntaxGenerator.IfStatement(
syntaxGenerator.ValueEqualsExpression(
syntaxGenerator.IdentifierName("behavior"),
syntaxGenerator.MemberAccessExpression(mockBehaviorType, "Loose")),
new[]
{
syntaxGenerator.InvocationExpression(syntaxGenerator.IdentifierName("ConfigureLooseBehavior"))
})
});
}
示例8: CreateDisposeMethods
private IEnumerable<SyntaxNode> CreateDisposeMethods(Compilation compilation, SyntaxGenerator g, GenerationNameTable nameTable, bool suppressWarningComments)
{
yield return g.AddWarningCommentIf(!suppressWarningComments,
g.MethodDeclaration(
"Dispose",
accessibility: Accessibility.Public,
statements: new SyntaxNode[]
{
g.InvocationExpression(
g.MemberAccessExpression(
g.ThisExpression(),
"Dispose"
),
g.TrueLiteralExpression()
),
g.InvocationExpression(
g.MemberAccessExpression(
g.TypeExpression(compilation.RequireTypeByMetadataName("System.GC")),
"SuppressFinalize"
),
g.ThisExpression()
)
}
))
.PrependLeadingTrivia(g.CreateRegionTrivia("IDisposable"));
yield return g.AddWarningCommentIf(!suppressWarningComments, g.MethodDeclaration(
"Dispose",
parameters: new SyntaxNode[] { g.ParameterDeclaration("disposing", g.TypeExpression(SpecialType.System_Boolean)) },
accessibility: Accessibility.Private,
statements: new SyntaxNode[]
{
g.IfStatement(
g.ValueEqualsExpression(
g.IdentifierName("disposing"),
g.TrueLiteralExpression()
),
new SyntaxNode[]
{
g.TryCatchStatement(
new SyntaxNode[]
{
g.ExpressionStatement(
g.InvocationExpression(
g.MemberAccessExpression(
g.ThisExpression(),
nameTable[MemberNames.CloseProxyMethod]
),
g.FalseLiteralExpression()
)
)
},
new SyntaxNode[]
{
g.CatchClause(new SyntaxNode [0])
}
)
}
)
}
)).AddTrailingTrivia(g.CreateEndRegionTrivia());
}
示例9: CreateCloseProxyMethod
private SyntaxNode CreateCloseProxyMethod(Compilation compilation, SyntaxGenerator g, GenerationNameTable nameTable, bool asAsync)
{
return
g.MethodDeclaration(
asAsync ? nameTable[MemberNames.CloseProxyAsyncMethod] : nameTable[MemberNames.CloseProxyMethod],
returnType: asAsync ? g.TypeExpression(compilation.RequireType<Task>()) : null,
parameters: new SyntaxNode[] { g.ParameterDeclaration("alwaysAbort", g.TypeExpression(SpecialType.System_Boolean)) },
modifiers: asAsync ? DeclarationModifiers.Async : DeclarationModifiers.None,
accessibility: Accessibility.Private,
statements: new SyntaxNode[]
{
g.IfStatement(
g.ReferenceNotEqualsExpression(
g.IdentifierName(nameTable[MemberNames.CachedProxyField]),
g.NullLiteralExpression()
),
new SyntaxNode[]
{
g.LocalDeclarationStatement(
"proxy",
g.TryCastExpression(
g.MemberAccessExpression(
g.ThisExpression(),
nameTable[MemberNames.CachedProxyField]
),
compilation.RequireTypeByMetadataName("System.ServiceModel.ICommunicationObject")
)
),
g.TryFinallyStatement(
new SyntaxNode[]
{
AwaitExpressionIfAsync(g, asAsync,
g.InvocationExpression(
g.IdentifierName(asAsync ? nameTable[MemberNames.CloseProxyAsyncMethod] : nameTable[MemberNames.CloseProxyMethod]),
g.IdentifierName("proxy"),
g.IdentifierName("alwaysAbort")
)
)
},
new SyntaxNode[]
{
g.AssignmentStatement(
g.MemberAccessExpression(
g.ThisExpression(),
nameTable[MemberNames.CachedProxyField]
),
g.NullLiteralExpression()
)
}
)
}
)
}
);
}
示例10: CreateStaticCloseProxyMethod
private SyntaxNode CreateStaticCloseProxyMethod(Compilation compilation, SyntaxGenerator g, GenerationNameTable nameTable, bool asAsync)
{
//private static void CloseProxy(System.ServiceModel.ICommunicationObject proxy, bool alwaysAbort)
//{
// try
// {
// if (proxy != null && proxy.State != System.ServiceModel.CommunicationState.Closed)
// {
// if (!alwaysAbort && proxy.State != System.ServiceModel.CommunicationState.Faulted)
// {
// proxy.Close();
// }
// else
// {
// proxy.Abort();
// }
// }
// }
// catch (System.ServiceModel.CommunicationException)
// {
// proxy.Abort();
// }
// catch (System.TimeoutException)
// {
// proxy.Abort();
// }
// catch
// {
// proxy.Abort();
// throw;
// }
//}
return g.MethodDeclaration(
asAsync ? nameTable[MemberNames.CloseProxyAsyncMethod] : nameTable[MemberNames.CloseProxyMethod],
accessibility: Accessibility.Private,
returnType: asAsync ? g.TypeExpression(compilation.RequireType<Task>()) : null,
modifiers: (asAsync ? DeclarationModifiers.Async : DeclarationModifiers.None) | DeclarationModifiers.Static,
parameters: new SyntaxNode[]
{
g.ParameterDeclaration("proxy", g.TypeExpression(compilation.RequireTypeByMetadataName("System.ServiceModel.ICommunicationObject"))),
g.ParameterDeclaration("alwaysAbort", g.TypeExpression(SpecialType.System_Boolean))
},
statements: new SyntaxNode[]
{
g.TryCatchStatement(
new SyntaxNode[]
{
// if (proxy != null && proxy.State != System.ServiceModel.CommunicationState.Closed)
g.IfStatement(
g.LogicalAndExpression(
g.ReferenceNotEqualsExpression(
g.IdentifierName("proxy"),
g.NullLiteralExpression()
),
g.ValueNotEqualsExpression(
g.MemberAccessExpression(
g.IdentifierName("proxy"),
"State"
),
g.DottedName("System.ServiceModel.CommunicationState.Closed")
)
),
new SyntaxNode[]
{
// if (!alwaysAbort && proxy.State != System.ServiceModel.CommunicationState.Faulted)
g.IfStatement(
g.LogicalAndExpression(
g.LogicalNotExpression(
g.IdentifierName("alwaysAbort")
),
g.ValueNotEqualsExpression(
g.MemberAccessExpression(
g.IdentifierName("proxy"),
"State"
),
g.DottedName("System.ServiceModel.CommunicationState.Faulted")
)
),
new SyntaxNode[]
{
g.ExpressionStatement(
asAsync ?
// await System.Threading.Tasks.Task.Factory.FromAsync(proxy.BeginClose, proxy.EndClose, null).ConfigureAwait(false);
AwaitExpression(g,
g.InvocationExpression(
g.DottedName("System.Threading.Tasks.Task.Factory.FromAsync"),
g.DottedName("proxy.BeginClose"),
g.DottedName("proxy.EndClose"),
g.NullLiteralExpression()
)
)
:
// proxy.Close();
g.InvocationExpression(
g.MemberAccessExpression(
g.IdentifierName("proxy"),
"Close"
)
//.........这里部分代码省略.........
示例11: GenerateClientClass
public Task<ClassDeclarationSyntax> GenerateClientClass(SemanticModel semanticModel, SyntaxGenerator gen, INamedTypeSymbol proxyInterface, string name, Accessibility accessibility, bool includeCancellableAsyncMethods, bool suppressWarningComments, MemberAccessibility constructorAccessibility, bool withInternalProxy)
{
if (name == null)
{
if (proxyInterface.Name.StartsWith("I"))
name = proxyInterface.Name.Substring(1);
if (name.EndsWith("Proxy"))
name = name.Substring(0, name.Length - "Proxy".Length);
if (!name.EndsWith("Client"))
name = name + "Client";
}
SyntaxNode targetClass = gen.ClassDeclaration(name,
baseType: gen.TypeExpression(semanticModel.Compilation.RequireType<MarshalByRefObject>()),
accessibility: accessibility,
modifiers: DeclarationModifiers.Sealed);
targetClass = gen.AddWarningCommentIf(!suppressWarningComments, targetClass);
targetClass = gen.AddInterfaceType(targetClass, gen.TypeExpression(semanticModel.Compilation.GetSpecialType(SpecialType.System_IDisposable)));
targetClass = gen.AddInterfaceType(targetClass, gen.TypeExpression(proxyInterface));
IEnumerable<IMethodSymbol> methods = GetOperationContractMethods(semanticModel.Compilation, proxyInterface).ToArray();
GenerationNameTable nameTable = new GenerationNameTable(methods.Select(m => m.Name).Concat(new[] { name }));
#region Private Fields
// ==> private IProxy m_cachedProxy;
SyntaxNode cachedProxyField =
gen.FieldDeclaration(nameTable[MemberNames.CachedProxyField], gen.TypeExpression(proxyInterface), Accessibility.Private, DeclarationModifiers.None)
.PrependLeadingTrivia(gen.CreateRegionTrivia("Private Fields"));
targetClass = gen.AddMembers(targetClass, cachedProxyField);
// ==> private readonly Func<IProxy> m_proxyFactory;
SyntaxNode proxyFactoryTypeExpression = gen.TypeExpression(semanticModel.Compilation.RequireTypeByMetadataName("System.Func`1").Construct(proxyInterface));
targetClass = gen.AddMembers(targetClass, gen.FieldDeclaration(nameTable[MemberNames.ProxyFactoryField], proxyFactoryTypeExpression, Accessibility.Private, DeclarationModifiers.ReadOnly)
.AddTrailingTrivia(gen.CreateEndRegionTrivia()).AddNewLineTrivia());
#endregion
#region Constructors
// Constructor
SyntaxNode constructor = gen.ConstructorDeclaration(
parameters: new[] { gen.ParameterDeclaration("proxyFactory", proxyFactoryTypeExpression) },
accessibility: withInternalProxy ? Accessibility.Private : ToAccessibility(constructorAccessibility)
);
constructor = gen.AddWarningCommentIf(!suppressWarningComments, constructor);
constructor = constructor.PrependLeadingTrivia(gen.CreateRegionTrivia("Constructors"));
constructor = gen.WithStatements(constructor,
new[]
{
// ==> if (proxyFactory == null)
// ==> throw new System.ArgumentNullException("proxyFactory");
gen.ThrowIfNullStatement("proxyFactory"),
// ==> m_proxyFactory = proxyFactory
gen.AssignmentStatement(
gen.MemberAccessExpression(
gen.ThisExpression(),
gen.IdentifierName(nameTable[MemberNames.ProxyFactoryField])),
gen.IdentifierName("proxyFactory")
)
}
).AddNewLineTrivia();
if (!withInternalProxy)
constructor = constructor.AddTrailingTrivia(gen.CreateEndRegionTrivia()).AddNewLineTrivia();
targetClass = gen.AddMembers(targetClass, constructor);
ClassDeclarationSyntax proxyClass = null;
if (withInternalProxy)
{
IEnumerable<IMethodSymbol> ctors;
proxyClass = GenerateProxyClass(semanticModel, gen, proxyInterface, nameTable[MemberNames.ProxyClass], Accessibility.Private, suppressWarningComments, MemberAccessibility.Public, out ctors)
.PrependLeadingTrivia(gen.CreateRegionTrivia("Proxy Class").Insert(0, gen.NewLine()))
.AddTrailingTrivia(gen.CreateEndRegionTrivia());
// Generate one constructor for each of the proxy's constructors.
foreach (var ctorEntry in ctors.AsSmartEnumerable())
{
var ctor = ctorEntry.Value;
var targetCtor = gen.ConstructorDeclaration(ctor);
var lambda = gen.ValueReturningLambdaExpression(
gen.ObjectCreationExpression(gen.IdentifierName(gen.GetName(proxyClass)), ctor.Parameters.Select(p => gen.IdentifierName(p.Name)))
);
targetCtor = gen.WithThisConstructorInitializer(targetCtor, new[] { lambda });
//.........这里部分代码省略.........