当前位置: 首页>>代码示例>>C#>>正文


C# RefactoringContext.GetResolverStateBefore方法代码示例

本文整理汇总了C#中RefactoringContext.GetResolverStateBefore方法的典型用法代码示例。如果您正苦于以下问题:C# RefactoringContext.GetResolverStateBefore方法的具体用法?C# RefactoringContext.GetResolverStateBefore怎么用?C# RefactoringContext.GetResolverStateBefore使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在RefactoringContext的用法示例。


在下文中一共展示了RefactoringContext.GetResolverStateBefore方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetActions

		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var expr = GetCreatePropertyOrFieldNode(context);
			if (expr == null)
				yield break;
			if (!(expr is MemberReferenceExpression))
				yield break;
			var propertyName = CreatePropertyAction.GetPropertyName(expr);
			if (propertyName == null)
				yield break;
			if (IsInvocationTarget(expr))
				yield break;
			var statement = expr.GetParent<Statement>();
			if (statement == null)
				yield break;
			if (!(context.Resolve(expr).IsError))
				yield break;
			var guessedType = CreateFieldAction.GuessType(context, expr);
			if (guessedType == null || guessedType.Kind != TypeKind.Enum)
				yield break;
			var state = context.GetResolverStateBefore(expr);
			if (state.CurrentMember == null || state.CurrentTypeDefinition == null)
				yield break;

			yield return new CodeAction(context.TranslateString("Create enum value"), script => {
				var decl = new EnumMemberDeclaration {
					Name = propertyName
				};
				script.InsertWithCursor(context.TranslateString("Create enum value"), guessedType.GetDefinition (), decl);
			});
			
		}
开发者ID:RainsSoft,项目名称:playscript-monodevelop,代码行数:32,代码来源:CreateEnumValue.cs

示例2: GetActions

		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var type = context.GetNode<AstType>();
			if (type == null || type.Role != Roles.BaseType)
				yield break;
			var state = context.GetResolverStateBefore(type);
			if (state.CurrentTypeDefinition == null)
				yield break;

			var resolveResult = context.Resolve(type);
			if (resolveResult.Type.Kind != TypeKind.Interface)
				yield break;

			var toImplement = ImplementInterfaceAction.CollectMembersToImplement(
				state.CurrentTypeDefinition,
				resolveResult.Type,
				false
			);
			if (toImplement.Count == 0)
				yield break;

			yield return new CodeAction(context.TranslateString("Implement interface explicit"), script => {
				script.InsertWithCursor(
					context.TranslateString("Implement Interface"),
					state.CurrentTypeDefinition,
					ImplementInterfaceAction.GenerateImplementation (context, toImplement.Select (t => Tuple.Create (t.Item1, true)))
				);
			});
		}
开发者ID:Gobiner,项目名称:ILSpy,代码行数:29,代码来源:ImplementInterfaceExplicitAction.cs

示例3: GetActionsForAddNamespaceUsing

        IEnumerable<CodeAction> GetActionsForAddNamespaceUsing(RefactoringContext context, AstNode node)
        {
            var nrr = context.Resolve(node) as NamespaceResolveResult;
            if (nrr == null)
                return EmptyList<CodeAction>.Instance;

            var trr = context.Resolve(node.Parent) as TypeResolveResult;
            if (trr == null)
                return EmptyList<CodeAction>.Instance;
            ITypeDefinition typeDef = trr.Type.GetDefinition();
            if (typeDef == null)
                return EmptyList<CodeAction>.Instance;

            IList<IType> typeArguments;
            ParameterizedType parameterizedType = trr.Type as ParameterizedType;
            if (parameterizedType != null)
                typeArguments = parameterizedType.TypeArguments;
            else
                typeArguments = EmptyList<IType>.Instance;

            var resolver = context.GetResolverStateBefore(node.Parent);
            if (resolver.ResolveSimpleName(typeDef.Name, typeArguments) is UnknownIdentifierResolveResult) {
                // It's possible to remove the explicit namespace usage and introduce a using instead
                return new[] { NewUsingAction(context, node, typeDef.Namespace) };
            }
            return EmptyList<CodeAction>.Instance;
        }
开发者ID:segaman,项目名称:NRefactory,代码行数:27,代码来源:AddUsingAction.cs

示例4: GetActions

		public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var service = (CodeGenerationService)context.GetService(typeof(CodeGenerationService)); 
			if (service == null)
				yield break;

			var type = context.GetNode<AstType>();
			if (type == null || type.Role != Roles.BaseType)
				yield break;
			var state = context.GetResolverStateBefore(type);
			if (state.CurrentTypeDefinition == null)
				yield break;

			var resolveResult = context.Resolve(type);
			if (resolveResult.Type.Kind != TypeKind.Interface)
				yield break;

			bool interfaceMissing;
			var toImplement = ImplementInterfaceAction.CollectMembersToImplement(
				state.CurrentTypeDefinition,
				resolveResult.Type,
				false,
				out interfaceMissing
			);
			if (toImplement.Count == 0)
				yield break;

			yield return new CodeAction(context.TranslateString("Implement interface explicit"), script =>
				script.InsertWithCursor(
					context.TranslateString("Implement Interface"),
					state.CurrentTypeDefinition,
					(s, c) => ImplementInterfaceAction.GenerateImplementation (c, toImplement.Select (t => Tuple.Create (t.Item1, true)), interfaceMissing).ToList()
				)
			, type);
		}
开发者ID:0xb1dd1e,项目名称:NRefactory,代码行数:35,代码来源:ImplementInterfaceExplicitAction.cs

示例5: GetActions

		public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var service = (CodeGenerationService)context.GetService(typeof(CodeGenerationService)); 
			if (service == null)
				yield break;

			var type = context.GetNode<AstType>();
			if (type == null || type.Role != Roles.BaseType)
				yield break;
			var state = context.GetResolverStateBefore(type);
			if (state.CurrentTypeDefinition == null)
				yield break;

			var resolveResult = context.Resolve(type);
			if (resolveResult.Type.Kind != TypeKind.Class || resolveResult.Type.GetDefinition() == null || !resolveResult.Type.GetDefinition().IsAbstract)
				yield break;

			var toImplement = CollectMembersToImplement(state.CurrentTypeDefinition, resolveResult.Type);
			if (toImplement.Count == 0)
				yield break;

			yield return new CodeAction(
				context.TranslateString("Implement abstract members"), 
				script => script.InsertWithCursor(
					context.TranslateString("Implement abstract members"), 
					state.CurrentTypeDefinition, (s, c) => ImplementInterfaceAction.GenerateImplementation(c, toImplement.Select(m => Tuple.Create(m, false)), true)
				.Select(entity => {
					var decl = entity as EntityDeclaration;
					if (decl != null)
						decl.Modifiers |= Modifiers.Override;
					return entity;
				}).ToList()), type);
		}
开发者ID:0xb1dd1e,项目名称:NRefactory,代码行数:33,代码来源:ImplementAbstractMembersAction.cs

示例6: GetActionsFromMemberReferenceExpression

		IEnumerable<CodeAction> GetActionsFromMemberReferenceExpression(RefactoringContext context, MemberReferenceExpression invocation)
		{
			if (!(context.Resolve(invocation).IsError)) 
					yield break;

			var methodName = invocation.MemberName;
			var guessedType = TypeGuessing.GuessType(context, invocation);
			if (guessedType.Kind != TypeKind.Delegate)
					yield break;
			var invocationMethod = guessedType.GetDelegateInvokeMethod();
			var state = context.GetResolverStateBefore(invocation);
			if (state.CurrentTypeDefinition == null)
				yield break;
			ResolveResult targetResolveResult = context.Resolve(invocation.Target);
			bool createInOtherType = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());

			bool isStatic;
			if (createInOtherType) {
				if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
					yield break;
				isStatic = targetResolveResult is TypeResolveResult;
				if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
					yield break;
			} else {
				if (state.CurrentMember == null)
					yield break;
				isStatic = state.CurrentMember.IsStatic || state.CurrentTypeDefinition.IsStatic;
			}

//			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(methodName, AffectedEntity.Method, Modifiers.Private, isStatic)) { 
//				yield break;
//			}

			yield return CreateAction(
				context, 
				invocation,
				methodName, 
				context.CreateShortType(invocationMethod.ReturnType),
				invocationMethod.Parameters.Select(parameter => new ParameterDeclaration(context.CreateShortType(parameter.Type), parameter.Name) { 
					ParameterModifier = GetModifiers(parameter)
				}),
				createInOtherType,
				isStatic,
				targetResolveResult);
		}
开发者ID:qhta,项目名称:NRefactory,代码行数:46,代码来源:CreateMethodDeclarationAction.cs

示例7: GetActions

		public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var loop = GetForeachStatement (context);
			if (loop == null) {
				yield break;
			}

			if (context.GetResolverStateBefore(loop)
			    .LookupSimpleNameOrTypeName("Enumerable", new List<IType>(), NameLookupMode.Type)
			    .Type.FullName != "System.Linq.Enumerable") {

				yield break;
			}

			var outputStatement = GetTransformedAssignmentExpression (context, loop);
			if (outputStatement == null) {
				yield break;
			}

			yield return new CodeAction(context.TranslateString("Convert foreach loop to LINQ expression"), script => {

				var prevSibling = loop.GetPrevSibling(node => node is Statement);

				Expression leftSide = outputStatement.Left;
				Expression rightSide = outputStatement.Right;

				Expression expressionToReplace = GetExpressionToReplace(prevSibling, leftSide);

				if (expressionToReplace != null) {
					Expression replacementExpression = rightSide.Clone();
					if (!IsZeroPrimitive(expressionToReplace)) {
						replacementExpression = new BinaryOperatorExpression(ParenthesizeIfNeeded(expressionToReplace).Clone(),
						                                                     BinaryOperatorType.Add,
						                                                     replacementExpression);
					}

					script.Replace(expressionToReplace, replacementExpression);
					script.Remove(loop);
				}
				else {
					script.Replace(loop, new ExpressionStatement(outputStatement));
				}

			}, loop);
		}
开发者ID:qhta,项目名称:NRefactory,代码行数:45,代码来源:AutoLinqSumAction.cs

示例8: GetActions

		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var expr = context.GetNode(n => n is IdentifierExpression || n is MemberReferenceExpression) as Expression;
			if (expr == null)
				yield break;

			if (expr is MemberReferenceExpression && !(((MemberReferenceExpression)expr).Target is ThisReferenceExpression))
				yield break;

			var propertyName = CreatePropertyAction.GetPropertyName(expr);
			if (propertyName == null)
				yield break;

			if (IsInvocationTarget(expr))
				yield break;
			var statement = expr.GetParent<Statement>();
			if (statement == null)
				yield break;
			if (!(context.Resolve(expr).IsError))
				yield break;
			var guessedType = CreateFieldAction.GuessAstType(context, expr);
			if (guessedType == null)
				yield break;
			var state = context.GetResolverStateBefore(expr);
			if (state.CurrentMember == null || state.CurrentTypeDefinition == null)
				yield break;

			bool isStatic = state.CurrentMember.IsStatic | state.CurrentTypeDefinition.IsStatic;

//			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(identifier.Identifier, AffectedEntity.Field, Modifiers.Private, isStatic)) { 
//				yield break;
//			}

			yield return new CodeAction(context.TranslateString("Create field"), script => {
				var decl = new FieldDeclaration() {
					ReturnType = guessedType,
					Variables = { new VariableInitializer(propertyName) }
				};
				if (isStatic)
					decl.Modifiers |= Modifiers.Static;
				script.InsertWithCursor(context.TranslateString("Create field"), Script.InsertPosition.Before, decl);
			});

		}
开发者ID:Gobiner,项目名称:ILSpy,代码行数:45,代码来源:CreateFieldAction.cs

示例9: GetActions

		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			var type = context.GetNode<AstType>();
			if (type == null || type.Role != Roles.BaseType)
				yield break;
			var state = context.GetResolverStateBefore(type);
			if (state.CurrentTypeDefinition == null)
				yield break;

			var resolveResult = context.Resolve(type);
			if (resolveResult.Type.Kind != TypeKind.Class || resolveResult.Type.GetDefinition() == null || !resolveResult.Type.GetDefinition().IsAbstract)
				yield break;

			yield break;
			/*
			yield return new CodeAction(context.TranslateString("Implement abstract members"), script => {
				script.InsertWithCursor(
					context.TranslateString("Implement abstract members"),
					state.CurrentTypeDefinition,
					ImplementInterfaceAction.GenerateImplementation (context, toImplement)
				);
			});*/
		}
开发者ID:nieve,项目名称:NRefactory,代码行数:23,代码来源:ImplementAbstractMembersAction.cs

示例10: GetActionsFromInvocation

		IEnumerable<CodeAction> GetActionsFromInvocation(RefactoringContext context, InvocationExpression invocation)
		{
			if (!(context.Resolve(invocation.Target).IsError)) 
				yield break;

			var methodName = GetMethodName(invocation);
			if (methodName == null)
				yield break;
			var state = context.GetResolverStateBefore(invocation);
			if (state.CurrentMember == null || state.CurrentTypeDefinition == null)
				yield break;
			var guessedType = invocation.Parent is ExpressionStatement ? new PrimitiveType("void") : TypeGuessing.GuessAstType(context, invocation);

			bool createInOtherType = false;
			ResolveResult targetResolveResult = null;
			if (invocation.Target is MemberReferenceExpression) {
				targetResolveResult = context.Resolve(((MemberReferenceExpression)invocation.Target).Target);
				createInOtherType = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());
			}

			bool isStatic;
			if (createInOtherType) {
				if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
					yield break;
				isStatic = targetResolveResult is TypeResolveResult;
				if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
					yield break;
			} else {
				isStatic = state.CurrentMember.IsStatic || state.CurrentTypeDefinition.IsStatic;
			}

//			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(methodName, AffectedEntity.Method, Modifiers.Private, isStatic)) { 
//				yield break;
//			}


			yield return CreateAction(
				context, 
				invocation,
				methodName, 
				guessedType,
				GenerateParameters(context, invocation.Arguments),
				createInOtherType,
				isStatic,
				targetResolveResult);
		}
开发者ID:qhta,项目名称:NRefactory,代码行数:47,代码来源:CreateMethodDeclarationAction.cs

示例11: GetActionsFromIdentifier

		IEnumerable<CodeAction> GetActionsFromIdentifier(RefactoringContext context, IdentifierExpression identifier)
		{
			if (!(context.Resolve(identifier).IsError))
				yield break;
			var methodName = identifier.Identifier;
			var guessedType = TypeGuessing.GuessType(context, identifier);
			if (guessedType.Kind != TypeKind.Delegate)
				yield break;
			var invocationMethod = guessedType.GetDelegateInvokeMethod();
			if (invocationMethod == null)
				yield break;
			var state = context.GetResolverStateBefore(identifier);
			if (state.CurrentMember == null || state.CurrentTypeDefinition == null)
				yield break;
			bool isStatic = state.CurrentMember.IsStatic || state.CurrentTypeDefinition.IsStatic;

			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
			if (service != null && !service.IsValidName(methodName, AffectedEntity.Method, Modifiers.Private, isStatic))
				yield break;

			yield return CreateAction(
				context, 
				identifier,
				methodName, 
				context.CreateShortType(invocationMethod.ReturnType),
				invocationMethod.Parameters.Select(parameter => new ParameterDeclaration(context.CreateShortType(parameter.Type), parameter.Name) { 
					ParameterModifier = GetModifiers(parameter)
				}),
				false,
				isStatic,
				null);
		}
开发者ID:qhta,项目名称:NRefactory,代码行数:32,代码来源:CreateMethodDeclarationAction.cs

示例12: GetActions

		public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			bool hasIndexAccess;
			var foreachStatement = GetForeachStatement(context, out hasIndexAccess);
			if (foreachStatement == null || foreachStatement.EmbeddedStatement == null)
				yield break;
			var state = context.GetResolverStateBefore (foreachStatement.EmbeddedStatement);
			string name = GetName(state, VariableNames);
			if (name == null) // very unlikely, but just in case ...
				yield break;

			yield return new CodeAction(context.TranslateString("Convert 'foreach' loop to 'for'"), script => {
				var result = context.Resolve(foreachStatement.InExpression);
				var countProperty = GetCountProperty(result.Type);
				var inExpression = foreachStatement.InExpression;

				var initializer = hasIndexAccess ? new VariableDeclarationStatement(new PrimitiveType("int"), name, new PrimitiveExpression(0)) :
				                  new VariableDeclarationStatement(new SimpleType("var"), name, new InvocationExpression(new MemberReferenceExpression (inExpression.Clone (), "GetEnumerator")));
				var id1 = new IdentifierExpression(name);
				var id2 = id1.Clone();
				var id3 = id1.Clone();
				Statement declarationStatement = null;
				if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression) {
					string listName = GetName(state, CollectionNames) ?? "col";
					declarationStatement = new VariableDeclarationStatement (
						new PrimitiveType ("var"),
						listName,
						inExpression.Clone ()
					);
					inExpression = new IdentifierExpression (listName);
				}

				var variableDeclarationStatement = new VariableDeclarationStatement(
					foreachStatement.VariableType.Clone(),
					foreachStatement.VariableName,
					hasIndexAccess ? (Expression)new IndexerExpression(inExpression.Clone(), id3) : new MemberReferenceExpression(id1, "Current")
				);

				var forStatement = new ForStatement {
					Initializers = { initializer },
					Condition = hasIndexAccess ? (Expression)new BinaryOperatorExpression (id1, BinaryOperatorType.LessThan, new MemberReferenceExpression (inExpression.Clone (), countProperty)) :
					            new InvocationExpression(new MemberReferenceExpression (id2, "MoveNext")),
					EmbeddedStatement = new BlockStatement {
						variableDeclarationStatement
					}
				};

				if (hasIndexAccess)
					forStatement.Iterators.Add(new UnaryOperatorExpression (UnaryOperatorType.PostIncrement, id2));

				if (foreachStatement.EmbeddedStatement is BlockStatement) {
					variableDeclarationStatement.Remove();
					var oldBlock = (BlockStatement)foreachStatement.EmbeddedStatement.Clone();
					if (oldBlock.Statements.Any()) {
						oldBlock.Statements.InsertBefore(oldBlock.Statements.First(), variableDeclarationStatement);
					} else {
						oldBlock.Statements.Add(variableDeclarationStatement);
					}
					forStatement.EmbeddedStatement = oldBlock;
				} else {
					forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
				}
				if (declarationStatement != null)
					script.InsertBefore (foreachStatement, declarationStatement);
				script.Replace (foreachStatement, forStatement);
				if (hasIndexAccess) {
					script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
				} else {
					script.Link (initializer.Variables.First ().NameToken, id1, id2);
				}
			}, foreachStatement);

			if (!hasIndexAccess)
				yield break;
			yield return new CodeAction(context.TranslateString("Convert 'foreach' loop to optimized 'for'"), script => {
				var result = context.Resolve(foreachStatement.InExpression);
				var countProperty = GetCountProperty(result.Type);

				var initializer = new VariableDeclarationStatement(new PrimitiveType("int"), name, new PrimitiveExpression(0));
				var id1 = new IdentifierExpression(name);
				var id2 = id1.Clone();
				var id3 = id1.Clone();
				var inExpression = foreachStatement.InExpression;
				Statement declarationStatement = null;
				if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression) {
					string listName = GetName(state, CollectionNames) ?? "col";
					declarationStatement = new VariableDeclarationStatement (
						new PrimitiveType ("var"),
						listName,
						inExpression.Clone ()
						);
					inExpression = new IdentifierExpression (listName);
				}

				var variableDeclarationStatement = new VariableDeclarationStatement(
					foreachStatement.VariableType.Clone(),
					foreachStatement.VariableName,
					new IndexerExpression(inExpression.Clone(), id3)
					);

//.........这里部分代码省略.........
开发者ID:sphynx79,项目名称:dotfiles,代码行数:101,代码来源:ConvertForeachToForAction.cs

示例13: GetActions

        public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
        {
            var indexer = context.GetNode<IndexerExpression>();
            if (indexer == null)
                yield break;
            if (!(context.Resolve(indexer).IsError))
                yield break;

            var state = context.GetResolverStateBefore(indexer);
            if (state.CurrentTypeDefinition == null)
                yield break;
            var guessedType = CreateFieldAction.GuessAstType(context, indexer);

            bool createInOtherType = false;
            ResolveResult targetResolveResult = null;
            targetResolveResult = context.Resolve(indexer.Target);
            createInOtherType = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());

            bool isStatic;
            if (createInOtherType) {
                if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
                    yield break;
                isStatic = targetResolveResult is TypeResolveResult;
                if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
                    yield break;
            } else {
                isStatic = indexer.Target is IdentifierExpression && state.CurrentMember.IsStatic;
            }

            yield return new CodeAction(context.TranslateString("Create indexer"), script => {
                var decl = new IndexerDeclaration() {
                    ReturnType = guessedType,
                    Getter = new Accessor() {
                        Body = new BlockStatement() {
                            new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                        }
                    },
                    Setter = new Accessor() {
                        Body = new BlockStatement() {
                            new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                        }
                    },
                };
                decl.Parameters.AddRange(CreateMethodDeclarationAction.GenerateParameters(context, indexer.Arguments));
                if (isStatic)
                    decl.Modifiers |= Modifiers.Static;

                if (createInOtherType) {
                    if (targetResolveResult.Type.Kind == TypeKind.Interface) {
                        decl.Getter.Body = null;
                        decl.Setter.Body = null;
                        decl.Modifiers = Modifiers.None;
                    } else {
                        decl.Modifiers |= Modifiers.Public;
                    }

                    script.InsertWithCursor(context.TranslateString("Create indexer"), targetResolveResult.Type.GetDefinition(), (s, c) => decl);
                    return;
                }

                script.InsertWithCursor(context.TranslateString("Create indexer"), Script.InsertPosition.Before, decl);
            }, indexer);
        }
开发者ID:porcus,项目名称:NRefactory,代码行数:63,代码来源:CreateIndexerAction.cs

示例14: GetActions

        public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
        {
            var identifier = CreateFieldAction.GetCreatePropertyOrFieldNode (context);
            if (identifier == null)
                yield break;
            if (CreateFieldAction.IsInvocationTarget(identifier))
                yield break;

            var propertyName = GetPropertyName(identifier);
            if (propertyName == null)
                yield break;

            var statement = context.GetNode<Statement>();
            if (statement == null)
                yield break;

            if (!(context.Resolve(identifier).IsError))
                yield break;

            var guessedType = CreateFieldAction.GuessAstType(context, identifier);
            if (guessedType == null)
                yield break;
            var state = context.GetResolverStateBefore(identifier);
            if (state.CurrentTypeDefinition == null)
                yield break;

            bool createInOtherType = false;
            ResolveResult targetResolveResult = null;
            if (identifier is MemberReferenceExpression) {
                targetResolveResult = context.Resolve(((MemberReferenceExpression)identifier).Target);
                if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
                    yield break;
                createInOtherType = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());
            }

            bool isStatic = targetResolveResult is TypeResolveResult;
            if (createInOtherType) {
                if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
                    yield break;
            } else {
                if (state.CurrentMember == null)
                    yield break;
                isStatic |= state.CurrentTypeDefinition.IsStatic;
                if (targetResolveResult == null)
                    isStatic |= state.CurrentMember.IsStatic;
            }
            isStatic &= !(identifier is NamedExpression);

            //			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
            //			if (service != null && !service.IsValidName(propertyName, AffectedEntity.Property, Modifiers.Private, isStatic)) {
            //				yield break;
            //			}

            yield return new CodeAction(context.TranslateString("Create property"), script => {
                var decl = new PropertyDeclaration() {
                    ReturnType = guessedType,
                    Name = propertyName,
                    Getter = new Accessor(),
                    Setter = new Accessor()
                };
                if (isStatic)
                    decl.Modifiers |= Modifiers.Static;

                if (createInOtherType) {
                    if (targetResolveResult.Type.Kind == TypeKind.Interface) {
                        decl.Modifiers = Modifiers.None;
                    } else {
                        decl.Modifiers |= Modifiers.Public;
                    }
                    script.InsertWithCursor(
                        context.TranslateString("Create property"),
                        targetResolveResult.Type.GetDefinition(),
                        (s, c) => decl);

                    return;
                }

                script.InsertWithCursor(context.TranslateString("Create property"), Script.InsertPosition.Before, decl);

            }, identifier.GetNodeAt(context.Location));
        }
开发者ID:porcus,项目名称:NRefactory,代码行数:81,代码来源:CreatePropertyAction.cs

示例15: GetActions

        public override IEnumerable<CodeAction> GetActions(RefactoringContext context)
        {
            var foreachStatement = GetForeachStatement(context);
            if (foreachStatement == null) {
                yield break;
            }

            var state = context.GetResolverStateBefore (foreachStatement.EmbeddedStatement);
            string name = GetName(state, VariableNames);
            if (name == null) // very unlikely, but just in case ...
                yield break;

            yield return new CodeAction(context.TranslateString("Convert 'foreach' loop to 'for'"), script => {
                var result = context.Resolve(foreachStatement.InExpression);
                var countProperty = GetCountProperty(result.Type);

                // TODO: use another variable name if 'i' is already in use
                var initializer = new VariableDeclarationStatement(new PrimitiveType("int"), name, new PrimitiveExpression(0));
                var id1 = new IdentifierExpression(name);
                var id2 = id1.Clone();
                var id3 = id1.Clone();
                var inExpression = foreachStatement.InExpression;
                Statement declarationStatement = null;
                if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression) {
                    string listName = GetName(state, CollectionNames) ?? "col";
                    declarationStatement = new VariableDeclarationStatement (
                        new PrimitiveType ("var"),
                        listName,
                        inExpression.Clone ()
                    );
                    inExpression = new IdentifierExpression (listName);
                }

                var variableDeclarationStatement = new VariableDeclarationStatement(
                    foreachStatement.VariableType.Clone(),
                    foreachStatement.VariableName,
                    new IndexerExpression(inExpression.Clone(), id3)
                    );
                var forStatement = new ForStatement() {
                    Initializers = { initializer },
                    Condition = new BinaryOperatorExpression (id1, BinaryOperatorType.LessThan, new MemberReferenceExpression (inExpression.Clone (), countProperty)),
                    Iterators = { new ExpressionStatement (new UnaryOperatorExpression (UnaryOperatorType.PostIncrement, id2)) },
                    EmbeddedStatement = new BlockStatement {
                        variableDeclarationStatement
                    }
                };

                if (foreachStatement.EmbeddedStatement is BlockStatement) {
                    variableDeclarationStatement.Remove();
                    var oldBlock = (BlockStatement)foreachStatement.EmbeddedStatement.Clone();
                    if (oldBlock.Statements.Any()) {
                        oldBlock.Statements.InsertBefore(oldBlock.Statements.First(), variableDeclarationStatement);
                    } else {
                        oldBlock.Statements.Add(variableDeclarationStatement);
                    }
                    forStatement.EmbeddedStatement = oldBlock;
                } else {
                    forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
                }
                if (declarationStatement != null)
                    script.InsertBefore (foreachStatement, declarationStatement);
                script.Replace (foreachStatement, forStatement);
                script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
            }, foreachStatement);
        }
开发者ID:porcus,项目名称:NRefactory,代码行数:65,代码来源:ConvertForeachToForAction.cs


注:本文中的RefactoringContext.GetResolverStateBefore方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。