本文整理汇总了C#中Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax类的典型用法代码示例。如果您正苦于以下问题:C# ParameterSyntax类的具体用法?C# ParameterSyntax怎么用?C# ParameterSyntax使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ParameterSyntax类属于Microsoft.CodeAnalysis.CSharp.Syntax命名空间,在下文中一共展示了ParameterSyntax类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: IntroduceFieldFromConstructor
public static SyntaxNode IntroduceFieldFromConstructor(SyntaxNode root, ConstructorDeclarationSyntax constructorStatement, ParameterSyntax parameter)
{
var oldClass = constructorStatement.FirstAncestorOrSelf<ClassDeclarationSyntax>();
var newClass = oldClass;
var fieldName = parameter.Identifier.ValueText;
var fieldType = parameter.Type;
var members = ExtractMembersFromClass(oldClass.Members);
var addMember = false;
if (!members.Any(p => p.Key == fieldName && p.Value == fieldType.ToString()))
{
var identifierPostFix = 0;
while (members.Any(p => p.Key == fieldName))
fieldName = parameter.Identifier.ValueText + ++identifierPostFix;
addMember = true;
}
var assignmentField = SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(),
SyntaxFactory.IdentifierName(fieldName)), SyntaxFactory.IdentifierName(parameter.Identifier.ValueText)));
var newConstructor = constructorStatement.WithBody(constructorStatement.Body.AddStatements(assignmentField));
newClass = newClass.ReplaceNode(constructorStatement, newConstructor);
if (addMember)
{
var newField = SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(parameter.Type)
.WithVariables(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(fieldName)))))
.WithModifiers(SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword) }))
.WithAdditionalAnnotations(Formatter.Annotation);
newClass = newClass.WithMembers(newClass.Members.Insert(0, newField)).WithoutAnnotations(Formatter.Annotation);
}
var newRoot = root.ReplaceNode(oldClass, newClass);
return newRoot;
}
开发者ID:Vossekop,项目名称:code-cracker,代码行数:35,代码来源:IntroduceFieldFromConstructorCodeFixProvider.cs
示例2: GetActions
protected IEnumerable<CodeAction> GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, ParameterSyntax node)
{
if (!node.Identifier.Span.Contains(span))
yield break;
var parameter = node;
var bodyStatement = parameter.Parent.Parent.ChildNodes().OfType<BlockSyntax>().FirstOrDefault();
if (bodyStatement == null)
yield break;
var parameterSymbol = semanticModel.GetDeclaredSymbol(node);
var type = parameterSymbol.Type;
if (type == null || type.IsValueType || HasNotNullContract(semanticModel, parameterSymbol, bodyStatement))
yield break;
yield return CreateAction(
node.Identifier.Span
, t2 => {
var newBody = bodyStatement.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { CreateContractRequiresCall(node.Identifier.ToString()) }.Concat(bodyStatement.Statements)));
var newRoot = (CompilationUnitSyntax)root.ReplaceNode((SyntaxNode)bodyStatement, newBody);
if (UsingStatementNotPresent(newRoot)) newRoot = AddUsingStatement(node, newRoot);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
, "Add contract requiring parameter must not be null"
);
}
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:29,代码来源:ContractRequiresNotNullCodeRefactoringProvider.cs
示例3: GetParameterType
public static string GetParameterType(ParameterSyntax parameter)
{
return parameter
.DescendantNodes()
.First(node => node is PredefinedTypeSyntax || node is IdentifierNameSyntax)
.GetFirstToken()
.ValueText;
}
开发者ID:hakenr,项目名称:RoslynCodeRefactoringPlayground,代码行数:8,代码来源:RoslynHelpers.cs
示例4: ParameterTranslation
public ParameterTranslation(ParameterSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
{
Type = syntax.Type.Get<TypeTranslation>(this);
Identifier = syntax.Identifier.Get(this);
Modifiers = syntax.Modifiers.Get(this);
Default = syntax.Default.Get<EqualsValueClauseTranslation>(this);
}
开发者ID:asthomas,项目名称:TypescriptSyntaxPaste,代码行数:8,代码来源:ParameterTranslation.cs
示例5: VisitParameter
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
return SimplifyNode(
node,
newNode: base.VisitParameter(node),
parentNode: node.Parent,
simplifier: SimplifyParameter);
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:8,代码来源:CSharpMiscellaneousReducer.Rewriter.cs
示例6: GetAttributesForParameter
public static IEnumerable<AttributeSyntaxSymbolMapping> GetAttributesForParameter(ParameterSyntax parameter,
SemanticModel semanticModel)
{
return parameter.AttributeLists
.SelectMany(al => al.Attributes)
.Select(attr => new AttributeSyntaxSymbolMapping(attr,
semanticModel.GetSymbolInfo(attr).Symbol as IMethodSymbol))
.Where(attr => attr.Symbol != null);
}
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:9,代码来源:AttributeSyntaxSymbolMapping.cs
示例7: RemoveHungarianPrefix
private async Task<Solution> RemoveHungarianPrefix(Document document, ParameterSyntax token, CancellationToken cancellationToken)
{
var newName = DehungarianAnalyzer.SuggestDehungarianName(token.Identifier.Text);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var tokenSymbol = semanticModel.GetDeclaredSymbol(token, cancellationToken);
var originalSolution = document.Project.Solution;
var optionSet = originalSolution.Workspace.Options;
var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, tokenSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);
return newSolution;
}
开发者ID:CaptiveAire,项目名称:dehungarian,代码行数:10,代码来源:CodeFixProvider.cs
示例8: VisitParameter
public override void VisitParameter(ParameterSyntax node)
{
// ignore parameters in lambdaexpressions
if (node.IsWithinLambda())
return;
var parameter = new Parameter(
node.Identifier.ToString(),
(ITypeSymbol)_semantic.GetSymbolInfo(node.Type).Symbol);
_parameters.Add(parameter);
}
开发者ID:pgenfer,项目名称:mixinSharp,代码行数:10,代码来源:ParameterSyntaxReader.cs
示例9: AppendParameterToMethod
public static MethodDeclarationSyntax AppendParameterToMethod(MethodDeclarationSyntax method,
ParameterSyntax parameter)
{
if (method.ParameterList.Parameters.Any())
{
parameter = parameter.WithLeadingTrivia(SF.Space);
}
return method.WithParameterList(method.ParameterList.AddParameters(parameter));
}
开发者ID:cdsalmons,项目名称:OrleansTemplates,代码行数:10,代码来源:RoslynUtils.cs
示例10: CreateOperatorDeclaration
protected OperatorDeclarationSyntax CreateOperatorDeclaration(SyntaxKind kind, ParameterSyntax[] parameters, StatementSyntax statement)
{
return SyntaxFactory.OperatorDeclaration(
new SyntaxList<AttributeListSyntax>(),
SyntaxFactory.TokenList(new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword) }),
SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
SyntaxFactory.Token(kind),
SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)),
SyntaxFactory.Block(statement),
new SyntaxToken());
}
开发者ID:EkardNT,项目名称:Roslyn,代码行数:12,代码来源:CA2231CSharpCodeFixProvider.cs
示例11: ApplyFromODataUriAsync
private async Task<Document> ApplyFromODataUriAsync(Document document, ParameterSyntax node,
CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync();
var newParameter = node.WithAttributeLists(node.AttributeLists.Add(SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
SyntaxFactory.Attribute(
SyntaxFactory.IdentifierName("FromODataUri"))))));
var newRoot = root.ReplaceNode(node, newParameter);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument;
}
开发者ID:DualBrain,项目名称:DotNetAnalyzers,代码行数:15,代码来源:ODataFromODataUriCodeFix.cs
示例12: IntroduceField
private async Task<Solution> IntroduceField(Document document, ParameterSyntax paramDecl, CancellationToken cancellationToken)
{
var rootNode = await document.GetSyntaxRootAsync();
var rewriter = new IntroduceFieldRewriter(paramDecl);
rootNode = rewriter.Visit(rootNode);
var alterConstructorRewriter = new AlterConstructorRewriter(rewriter.GeneratedField, paramDecl.FirstAncestorOrSelf<ConstructorDeclarationSyntax>(), rewriteParams: false);
rootNode = alterConstructorRewriter.Visit(rootNode);
rootNode = Formatter.Format(rootNode, document.Project.Solution.Workspace);
// Produce a new solution that has all references to that type renamed, including the declaration.
return document.WithSyntaxRoot(rootNode).Project.Solution;
}
开发者ID:yohney,项目名称:common-refactorings-plugin,代码行数:15,代码来源:IntroduceFieldRefactoringProvider.cs
示例13: Create
public static SourceParameterSymbol Create(
Binder context,
Symbol owner,
TypeSymbol parameterType,
ParameterSyntax syntax,
RefKind refKind,
SyntaxToken identifier,
int ordinal,
bool isParams,
bool isExtensionMethodThis,
DiagnosticBag diagnostics)
{
var name = identifier.ValueText;
var locations = ImmutableArray.Create<Location>(new SourceLocation(identifier));
if (!isParams &&
!isExtensionMethodThis &&
(syntax.Default == null) &&
(syntax.AttributeLists.Count == 0) &&
!owner.IsPartialMethod())
{
return new SourceSimpleParameterSymbol(owner, parameterType, ordinal, refKind, name, locations);
}
if (isParams)
{
// touch the constructor in order to generate proper use-site diagnostics
Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(context.Compilation,
WellKnownMember.System_ParamArrayAttribute__ctor,
diagnostics,
identifier.Parent.GetLocation());
}
var syntaxRef = syntax.GetReference();
return new SourceComplexParameterSymbol(
owner,
ordinal,
parameterType,
refKind,
ImmutableArray<CustomModifier>.Empty,
false,
name,
locations,
syntaxRef,
ConstantValue.Unset,
isParams,
isExtensionMethodThis);
}
开发者ID:riversky,项目名称:roslyn,代码行数:48,代码来源:SourceParameterSymbol.cs
示例14: Parameter
public static string Parameter(ParameterSyntax param)
{
if (param.Type == null) return param.Identifier.Text;
if (param.Type is IdentifierNameSyntax)
{
return param.Identifier.Text + ": " + Type(((IdentifierNameSyntax)param.Type).Identifier.Text);
}
// TODO: Double check the variadic parameters handling
if (param.Modifiers.Any(mod => mod.ToString() == "params"))
{
return param.Identifier.Text + ": " + SyntaxNode(((ArrayTypeSyntax)param.Type).ElementType) + "...";
}
return param.Identifier.Text + ": " + SyntaxNode(param.Type);
}
开发者ID:UIKit0,项目名称:SharpSwift,代码行数:17,代码来源:ParameterSyntaxParser.cs
示例15: SourcePrimaryConstructorParameterSymbolWithBackingField
internal SourcePrimaryConstructorParameterSymbolWithBackingField(
Symbol owner,
int ordinal,
TypeSymbol parameterType,
RefKind refKind,
string name,
ImmutableArray<Location> locations,
ParameterSyntax syntax,
ConstantValue defaultSyntaxValue,
bool isParams,
bool isExtensionMethodThis,
DiagnosticBag diagnostics
) : base(owner, ordinal, parameterType, refKind, ImmutableArray<CustomModifier>.Empty, false, name, locations, syntax.GetReference(), defaultSyntaxValue, isParams, isExtensionMethodThis)
{
bool modifierErrors;
var modifiers = SourceMemberFieldSymbol.MakeModifiers(owner.ContainingType, syntax.Identifier, syntax.Modifiers, diagnostics, out modifierErrors, ignoreParameterModifiers: true);
backingField = new BackingField(this, modifiers, modifierErrors, diagnostics);
}
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:19,代码来源:SourcePrimaryConstructorParameterSymbolWithBackingField.cs
示例16: CreateFieldAsync
private async Task<Document> CreateFieldAsync(CodeRefactoringContext context, ParameterSyntax parameter,
string paramName, string fieldName, CancellationToken cancellationToken)
{
var oldConstructor = parameter.Ancestors().OfType<ConstructorDeclarationSyntax>().First();
var newConstructor = oldConstructor.WithBody(oldConstructor.Body.AddStatements(
SyntaxFactory.ExpressionStatement(
SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(fieldName)),
SyntaxFactory.IdentifierName(paramName)))));
var oldClass = parameter.FirstAncestorOrSelf<ClassDeclarationSyntax>();
var oldClassWithNewCtor = oldClass.ReplaceNode(oldConstructor, newConstructor);
var fieldDeclaration = RoslynHelpers.CreateFieldDeclaration(RoslynHelpers.GetParameterType(parameter), fieldName);
var newClass = oldClassWithNewCtor
.WithMembers(oldClassWithNewCtor.Members.Insert(0, fieldDeclaration))
.WithAdditionalAnnotations(Formatter.Annotation);
var oldRoot = await context.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = oldRoot.ReplaceNode(oldClass, newClass);
return context.Document.WithSyntaxRoot(newRoot);
}
开发者ID:hakenr,项目名称:RoslynCodeRefactoringPlayground,代码行数:24,代码来源:CodeRefactoringProvider.cs
示例17: ReportParameterErrors
private static void ReportParameterErrors(
Symbol owner,
ParameterSyntax parameterSyntax,
SourceParameterSymbol parameter,
int firstDefault,
DiagnosticBag diagnostics)
{
TypeSymbol parameterType = parameter.Type;
int parameterIndex = parameter.Ordinal;
bool isDefault = parameterSyntax.Default != null;
SyntaxToken thisKeyword = parameterSyntax.Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword);
if (thisKeyword.Kind() == SyntaxKind.ThisKeyword && parameterIndex != 0)
{
// Report CS1100 on "this". Note that is a change from Dev10
// which reports the error on the type following "this".
// error CS1100: Method '{0}' has a parameter modifier 'this' which is not on the first parameter
diagnostics.Add(ErrorCode.ERR_BadThisParam, thisKeyword.GetLocation(), owner.Name);
}
else if (parameter.IsParams && owner.IsOperator())
{
// error CS1670: params is not valid in this context
diagnostics.Add(ErrorCode.ERR_IllegalParams, parameterSyntax.Modifiers.First(t => t.Kind() == SyntaxKind.ParamsKeyword).GetLocation());
}
else if (parameter.IsParams && !parameterType.IsSingleDimensionalArray())
{
// error CS0225: The params parameter must be a single dimensional array
diagnostics.Add(ErrorCode.ERR_ParamsMustBeArray, parameterSyntax.Modifiers.First(t => t.Kind() == SyntaxKind.ParamsKeyword).GetLocation());
}
else if (parameter.Type.IsStatic && !parameter.ContainingSymbol.ContainingType.IsInterfaceType())
{
// error CS0721: '{0}': static types cannot be used as parameters
diagnostics.Add(ErrorCode.ERR_ParameterIsStaticClass, owner.Locations[0], parameter.Type);
}
else if (firstDefault != -1 && parameterIndex > firstDefault && !isDefault && !parameter.IsParams)
{
// error CS1737: Optional parameters must appear after all required parameters
Location loc = parameterSyntax.Identifier.GetNextToken(includeZeroWidth: true).GetLocation(); //could be missing
diagnostics.Add(ErrorCode.ERR_DefaultValueBeforeRequiredValue, loc);
}
else if (parameter.RefKind != RefKind.None && parameter.Type.IsRestrictedType())
{
// CS1601: Cannot make reference to variable of type 'System.TypedReference'
diagnostics.Add(ErrorCode.ERR_MethodArgCantBeRefAny, parameterSyntax.Location, parameter.Type);
}
}
开发者ID:GloryChou,项目名称:roslyn,代码行数:47,代码来源:ParameterHelpers.cs
示例18: ReportDefaultParameterErrors
internal static bool ReportDefaultParameterErrors(
Binder binder,
Symbol owner,
ParameterSyntax parameterSyntax,
SourceParameterSymbol parameter,
BoundExpression defaultExpression,
DiagnosticBag diagnostics)
{
bool hasErrors = false;
// SPEC VIOLATION: The spec says that the conversion from the initializer to the
// parameter type is required to be either an identity or a nullable conversion, but
// that is not right:
//
// void M(short myShort = 10) {}
// * not an identity or nullable conversion but should be legal
//
// void M(object obj = (dynamic)null) {}
// * an identity conversion, but should be illegal
//
// void M(MyStruct? myStruct = default(MyStruct)) {}
// * a nullable conversion, but must be illegal because we cannot generate metadata for it
//
// Even if the expression is thoroughly illegal, we still want to bind it and
// stick it in the parameter because we want to be able to analyze it for
// IntelliSense purposes.
TypeSymbol parameterType = parameter.Type;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, parameterType, ref useSiteDiagnostics);
diagnostics.Add(defaultExpression.Syntax, useSiteDiagnostics);
// SPEC VIOLATION:
// By the spec an optional parameter initializer is required to be either:
// * a constant,
// * new S() where S is a value type
// * default(S) where S is a value type.
//
// The native compiler considers default(T) to be a valid
// initializer regardless of whether T is a value type
// reference type, type parameter type, and so on.
// We should consider simply allowing this in the spec.
//
// Also when valuetype S has a parameterless constructor,
// new S() is clearly not a constant expression and should produce an error
bool isValidDefaultValue = (defaultExpression.ConstantValue != null) ||
(defaultExpression.Kind == BoundKind.DefaultOperator) ||
(defaultExpression.Kind == BoundKind.ObjectCreationExpression &&
((BoundObjectCreationExpression)defaultExpression).Constructor.IsDefaultValueTypeConstructor());
SyntaxToken outKeyword;
SyntaxToken refKeyword;
SyntaxToken paramsKeyword;
SyntaxToken thisKeyword;
GetModifiers(parameterSyntax.Modifiers, out outKeyword, out refKeyword, out paramsKeyword, out thisKeyword);
// CONSIDER: We are inconsistent here regarding where the error is reported; is it
// CONSIDER: reported on the parameter name, or on the value of the initializer?
// CONSIDER: Consider making this consistent.
if (outKeyword.Kind() == SyntaxKind.OutKeyword)
{
// error CS1741: A ref or out parameter cannot have a default value
diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, outKeyword.GetLocation());
hasErrors = true;
}
else if (refKeyword.Kind() == SyntaxKind.RefKeyword)
{
// error CS1741: A ref or out parameter cannot have a default value
diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, refKeyword.GetLocation());
hasErrors = true;
}
else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword)
{
// error CS1751: Cannot specify a default value for a parameter array
diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, paramsKeyword.GetLocation());
hasErrors = true;
}
else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword)
{
// Only need to report CS1743 for the first parameter. The caller will
// have reported CS1100 if 'this' appeared on another parameter.
if (parameter.Ordinal == 0)
{
// error CS1743: Cannot specify a default value for the 'this' parameter
diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, thisKeyword.GetLocation());
hasErrors = true;
}
}
else if (!defaultExpression.HasAnyErrors && !isValidDefaultValue)
{
// error CS1736: Default parameter value for '{0}' must be a compile-time constant
diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, parameterSyntax.Default.Value.Location, parameterSyntax.Identifier.ValueText);
hasErrors = true;
}
else if (!conversion.Exists ||
conversion.IsUserDefined ||
conversion.IsIdentity && parameterType.SpecialType == SpecialType.System_Object && defaultExpression.Type.IsDynamic())
{
//.........这里部分代码省略.........
开发者ID:GloryChou,项目名称:roslyn,代码行数:101,代码来源:ParameterHelpers.cs
示例19: ReportDiagnostic
private static SyntaxNodeAnalysisContext ReportDiagnostic(SyntaxNodeAnalysisContext context, ParameterSyntax parameter)
{
var props = new Dictionary<string, string> { { "identifier", parameter.Identifier.Text } }.ToImmutableDictionary();
var diagnostic = Diagnostic.Create(Rule, parameter.GetLocation(), props, parameter.Identifier.ValueText);
context.ReportDiagnostic(diagnostic);
return context;
}
开发者ID:mrhmouse,项目名称:code-cracker,代码行数:7,代码来源:UnusedParametersAnalyzer.cs
示例20: IdentifierRefersToParam
private static bool IdentifierRefersToParam(IdentifierNameSyntax iName, ParameterSyntax param)
{
if (iName.Identifier.ToString() != param.Identifier.ToString())
return false;
var mae = iName.Parent as MemberAccessExpressionSyntax;
if (mae == null)
return true;
return mae.DescendantNodes().FirstOrDefault() == iName;
}
开发者ID:mrhmouse,项目名称:code-cracker,代码行数:11,代码来源:UnusedParametersAnalyzer.cs
注:本文中的Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论