本文整理汇总了C#中MethodDeclaration类的典型用法代码示例。如果您正苦于以下问题:C# MethodDeclaration类的具体用法?C# MethodDeclaration怎么用?C# MethodDeclaration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MethodDeclaration类属于命名空间,在下文中一共展示了MethodDeclaration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ValidateMethod
private void ValidateMethod(MethodDeclaration method, List<string> list, CompilationResult result)
{
var name = method.Name;
if (String.IsNullOrWhiteSpace(name))
{
result.AddError(new CompilationMessage
{
FilePath = method.OriginatingTree != null ? method.OriginatingTree.FilePath : null,
Location = DocumentLocation.FromTreeNode(method.OriginatingTree, method.OriginatingNode),
Message = "All generated method calls must have a valid name."
});
return;
}
if (list.Contains(name))
{
result.AddError(new CompilationMessage
{
FilePath = method.OriginatingTree != null ? method.OriginatingTree.FilePath : null,
Location = DocumentLocation.FromTreeNode(method.OriginatingTree, method.OriginatingNode),
Message = "Method overloading is not supported. Consider using optional parameters, " +
"or providing an alternate name using the ScriptName attribute."
});
return;
}
list.Add(name);
}
示例2: CreateFromExpression
CodeAction CreateFromExpression(RefactoringContext context, Expression expression)
{
var resolveResult = context.Resolve(expression);
if (resolveResult.IsError)
return null;
return new CodeAction(context.TranslateString("Extract method"), script => {
string methodName = "NewMethod";
var method = new MethodDeclaration() {
ReturnType = context.CreateShortType(resolveResult.Type),
Name = methodName,
Body = new BlockStatement() {
new ReturnStatement(expression.Clone())
}
};
if (!StaticVisitor.UsesNotStaticMember(context, expression))
method.Modifiers |= Modifiers.Static;
var task = script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);
Action<Task> replaceStatements = delegate {
var target = new IdentifierExpression(methodName);
script.Replace(expression, new InvocationExpression(target));
script.Link(target, method.NameToken);
};
if (task.IsCompleted) {
replaceStatements (null);
} else {
task.ContinueWith (replaceStatements, TaskScheduler.FromCurrentSynchronizationContext ());
}
});
}
示例3: GeneratePartialClassContextStub
static string GeneratePartialClassContextStub(ICodeContext context)
{
var member = context.CurrentMember;
if (member == null)
return "";
var builder = new TypeSystemAstBuilder();
MethodDeclaration decl;
if (member is IMethod) {
// If it's a method, convert it directly (including parameters + type parameters)
decl = (MethodDeclaration)builder.ConvertEntity(member);
} else {
// Otherwise, create a method anyways, and copy the parameters
decl = new MethodDeclaration();
if (member is IParameterizedMember) {
foreach (var p in ((IParameterizedMember)member).Parameters) {
decl.Parameters.Add(builder.ConvertParameter(p));
}
}
}
decl.Name = "__DebuggerStub__";
decl.ReturnType = builder.ConvertType(member.ReturnType);
decl.Modifiers = member.IsStatic ? Modifiers.Static : Modifiers.None;
// Make the method look like an explicit interface implementation so that it doesn't appear in CC
decl.PrivateImplementationType = new SimpleType("__DummyType__");
decl.Body = GenerateBodyFromContext(builder, context.LocalVariables.ToArray());
return WrapInType(context.CurrentTypeDefinition, decl).ToString();
}
示例4: Complete
public override void Complete(CompletionContext context)
{
var invokeSignature = delegateType.GetMethods(m => m.Name == "Invoke").Single();
var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
var builder = refactoringContext.CreateTypeSystemAstBuilder();
var handlerName = eventDefinition.Name;
var throwStatement = new ThrowStatement();
var decl = new MethodDeclaration {
ReturnType = refactoringContext.CreateShortType(invokeSignature.ReturnType),
Name = handlerName,
Body = new BlockStatement {
throwStatement
}
};
decl.Parameters.AddRange(invokeSignature.Parameters.Select(builder.ConvertParameter));
if (eventDefinition.IsStatic)
decl.Modifiers |= Modifiers.Static;
throwStatement.Expression = new ObjectCreateExpression(refactoringContext.CreateShortType("System", "NotImplementedException"));
// begin insertion
using (context.Editor.Document.OpenUndoGroup()) {
context.Editor.Document.Replace(context.StartOffset, context.Length, handlerName);
context.EndOffset = context.StartOffset + handlerName.Length;
using (var script = refactoringContext.StartScript()) {
script.InsertWithCursor(this.DisplayText, Script.InsertPosition.Before, decl)
// TODO : replace with Link, once that is implemented
.ContinueScript(() => script.Select(throwStatement));
}
}
}
示例5: AddPrivateImplementation
public static void AddPrivateImplementation(Ast.AstType type, MethodDeclaration method)
{
if (privateImplementations.ContainsKey(type))
privateImplementations[type].Add(method);
else
privateImplementations.Add(type, new List<MethodDeclaration>() { method });
}
示例6: VisitMethodDeclaration
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
// Only some methods are candidates for the warning
if (methodDeclaration.Body.IsNull)
return;
var methodResolveResult = ctx.Resolve(methodDeclaration) as MemberResolveResult;
if (methodResolveResult == null)
return;
var member = methodResolveResult.Member;
if (member.IsOverride)
return;
if (member.ImplementedInterfaceMembers.Any ())
return;
if (usedDelegates.UsedMethods.Any (m => m.MemberDefinition == member))
return;
if (currentTypeIsPartial && methodDeclaration.Parameters.Count == 2) {
if (methodDeclaration.Parameters.First().Name == "sender") {
// Looks like an event handler; the registration might be in the designer part
return;
}
}
foreach (var parameter in methodDeclaration.Parameters)
parameter.AcceptVisitor (this);
}
示例7: VisitMethodDeclaration
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
{
if (methodDeclaration.Modifiers.HasFlag(Modifiers.Abstract))
UnlockWith(methodDeclaration);
return base.VisitMethodDeclaration(methodDeclaration, data);
}
示例8: VisitMethodDeclaration
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
Guard.AgainstNullArgument("methodDeclaration", methodDeclaration);
IEnumerable<ParameterDeclaration> parameters = methodDeclaration
.GetChildrenByRole(Roles.Parameter)
.Select(x => (ParameterDeclaration)x.Clone());
var isVoid = false;
var isAsync = methodDeclaration.Modifiers.HasFlag(Modifiers.Async);
AstType returnType = methodDeclaration.GetChildByRole(Roles.Type).Clone();
var type = returnType as PrimitiveType;
if (type != null)
{
isVoid = string.Compare(
type.Keyword, "void", StringComparison.OrdinalIgnoreCase) == 0;
}
var methodType = new SimpleType(Identifier.Create(isVoid ? "Action" : "Func"));
IEnumerable<AstType> types = parameters.Select(
x => x.GetChildByRole(Roles.Type).Clone());
methodType
.TypeArguments
.AddRange(types);
if (!isVoid)
{
methodType.TypeArguments.Add(returnType);
}
var methodName = GetIdentifierName(methodDeclaration);
var methodBody = methodDeclaration
.GetChildrenByRole(Roles.Body)
.FirstOrDefault();
if (methodBody == null)
{
throw new NullReferenceException(string.Format("Method '{0}' has no method body", methodName));
}
methodBody = (BlockStatement)methodBody.Clone();
var prototype = new VariableDeclarationStatement { Type = methodType };
prototype.Variables.Add(new VariableInitializer(methodName));
var anonymousMethod = new AnonymousMethodExpression(methodBody, parameters) { IsAsync = isAsync };
var expression = new ExpressionStatement
{
Expression = new AssignmentExpression(
new IdentifierExpression(methodName),
anonymousMethod)
};
_methods.Add(new MethodVisitorResult
{
MethodDefinition = methodDeclaration,
MethodPrototype = prototype,
MethodExpression = expression
});
}
示例9: GeneratePartialClassContextStub
static string GeneratePartialClassContextStub(DebuggerCompletionContext context)
{
var compilation = SD.ParserService.GetCompilationForFile(context.FileName);
var file = SD.ParserService.GetExistingUnresolvedFile(context.FileName);
if (compilation == null || file == null)
return "";
var unresolvedMember = file.GetMember(context.Location);
if (unresolvedMember == null)
return "";
var member = unresolvedMember.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
if (member == null)
return "";
var builder = new TypeSystemAstBuilder();
MethodDeclaration decl;
if (unresolvedMember is IMethod) {
// If it's a method, convert it directly (including parameters + type parameters)
decl = (MethodDeclaration)builder.ConvertEntity(member);
} else {
// Otherwise, create a method anyways, and copy the parameters
decl = new MethodDeclaration();
if (member is IParameterizedMember) {
foreach (var p in ((IParameterizedMember)member).Parameters) {
decl.Parameters.Add(builder.ConvertParameter(p));
}
}
}
decl.Name = "__DebuggerStub__";
decl.ReturnType = builder.ConvertType(member.ReturnType);
decl.Modifiers = unresolvedMember.IsStatic ? Modifiers.Static : Modifiers.None;
// Make the method look like an explicit interface implementation so that it doesn't appear in CC
decl.PrivateImplementationType = new SimpleType("__DummyType__");
decl.Body = GenerateBodyFromContext(builder, context);
return WrapInType(unresolvedMember.DeclaringTypeDefinition, decl).ToString();
}
示例10: ConvertInterfaceImplementation
void ConvertInterfaceImplementation(MethodDeclaration member)
{
// members without modifiers are already C# explicit interface implementations, do not convert them
if (member.Modifier == Modifiers.None)
return;
while (member.InterfaceImplementations.Count > 0) {
InterfaceImplementation impl = member.InterfaceImplementations[0];
member.InterfaceImplementations.RemoveAt(0);
if (member.Name != impl.MemberName) {
MethodDeclaration newMember = new MethodDeclaration {
Name = impl.MemberName,
TypeReference = member.TypeReference,
Parameters = member.Parameters,
Body = new BlockStatement()
};
InvocationExpression callExpression = new InvocationExpression(new IdentifierExpression(member.Name));
foreach (ParameterDeclarationExpression decl in member.Parameters) {
callExpression.Arguments.Add(new IdentifierExpression(decl.ParameterName));
}
if (member.TypeReference.Type == "System.Void") {
newMember.Body.AddChild(new ExpressionStatement(callExpression));
} else {
newMember.Body.AddChild(new ReturnStatement(callExpression));
}
newMember.InterfaceImplementations.Add(impl);
InsertAfterSibling(member, newMember);
}
}
}
示例11: VisitMethodDeclaration
public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration)
{
base.VisitMethodDeclaration (methodDeclaration);
// partial method
if (methodDeclaration.Body.IsNull)
return;
var cfg = cfgBuilder.BuildControlFlowGraph (methodDeclaration.Body, ctx.Resolver,
ctx.CancellationToken);
var stack = new Stack<ControlFlowNode> ();
var visitedNodes = new HashSet<ControlFlowNode> ();
stack.Push (cfg [0]);
while (stack.Count > 0) {
var node = stack.Pop ();
// reach method's end
if (node.PreviousStatement == methodDeclaration.Body)
return;
// reach a return statement
if (node.NextStatement is ReturnStatement ||
node.NextStatement is ThrowStatement)
return;
foreach (var edge in node.Outgoing) {
if (visitedNodes.Add(edge.To))
stack.Push(edge.To);
}
}
AddIssue (methodDeclaration.NameToken,
ctx.TranslateString ("Method never reaches its end or a 'return' statement."));
}
示例12: VisitMethodDeclaration
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
{
Push();
object result = base.VisitMethodDeclaration(methodDeclaration, data);
Pop();
return result;
}
示例13: VisitMethodDeclaration
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
base.VisitMethodDeclaration (methodDeclaration);
var resolveResult = ctx.Resolve (methodDeclaration) as MemberResolveResult;
if (resolveResult == null)
return;
var method = resolveResult.Member as IMethod;
if (method == null)
return;
if (method.Parameters.Count == 0 || !method.Parameters.Last ().IsOptional)
return;
var overloads = method.DeclaringType.GetMethods(m => m.Name == method.Name && m.TypeParameters.Count == method.TypeParameters.Count)
.ToArray ();
var parameterNodes = methodDeclaration.Parameters.ToArray();
var parameters = new List<IParameter> ();
for (int i = 0; i < method.Parameters.Count; i++) {
if (method.Parameters [i].IsOptional &&
overloads.Any (m => ParameterListComparer.Instance.Equals (parameters, m.Parameters))) {
AddIssue (parameterNodes [i].StartLocation, parameterNodes.Last ().EndLocation,
ctx.TranslateString ("Method with optional parameter is hidden by overload"));
break;
}
parameters.Add (method.Parameters [i]);
}
}
示例14: VisitMethodDeclaration
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
{
if (methodDeclaration.IsExtensionMethod)
UnlockWith(methodDeclaration);
return base.VisitMethodDeclaration(methodDeclaration, data);
}
示例15: VisitMethodDeclaration
public override object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
{
if (methodDeclaration.Name.ToLower().Equals("main"))
{
if (methodDeclaration.IsExtensionMethod == false &&
methodDeclaration.Modifiers.HasFlag(Modifiers.Static) &&
methodDeclaration.ReturnType.ToString() == "void")
{
var firstParam = methodDeclaration.Parameters.FirstOrDefault();
if (firstParam != null && firstParam.Type.ToString().ToLower() == "string[]")
{
// The following is a lesson in awesomeness:
// Get all decendants of the method declaration that are IndexerExpressions,
// which points to an identifier with the name [of our args variable]
var indexerIdentifierExpressions = methodDeclaration.Descendants
.OfType<IndexerExpression>()
.Select(a => a.Target)
.OfType<IdentifierExpression>();
if (indexerIdentifierExpressions.Any(a => a.Identifier == firstParam.Name))
{
UnlockWith(firstParam);
}
}
}
}
return base.VisitMethodDeclaration(methodDeclaration, data);
}