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


C# TypeDeclaration.AddChild方法代码示例

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


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

示例1: VisitTypeDeclaration

		public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
		{
			base.VisitTypeDeclaration(typeDeclaration, data); // visit methods
			typeDeclaration.Attributes.Clear();
			typeDeclaration.BaseTypes.Clear();
			
			// add constructor accepting the wrapped object and the field holding the object
			FieldDeclaration fd = new FieldDeclaration(null, // no attributes
			                                           new TypeReference(typeDeclaration.Name),
			                                           Modifiers.Private);
			fd.Fields.Add(new VariableDeclaration("wrappedObject"));
			typeDeclaration.AddChild(fd);
			
			typeDeclaration.Name += "Wrapper";
			if (typeDeclaration.Type == ClassType.Interface) {
				typeDeclaration.Type = ClassType.Class;
				typeDeclaration.Name = typeDeclaration.Name.Substring(1);
			}
			ConstructorDeclaration cd = new ConstructorDeclaration(typeDeclaration.Name,
			                                                       Modifiers.Public,
			                                                       new List<ParameterDeclarationExpression>(),
			                                                       null);
			cd.Parameters.Add(new ParameterDeclarationExpression(fd.TypeReference,
			                                                     "wrappedObject"));
			// this.wrappedObject = wrappedObject;
			Expression fieldReference = new MemberReferenceExpression(new ThisReferenceExpression(),
			                                                         "wrappedObject");
			Expression assignment = new AssignmentExpression(fieldReference,
			                                                 AssignmentOperatorType.Assign,
			                                                 new IdentifierExpression("wrappedObject"));
			cd.Body = new BlockStatement();
			cd.Body.AddChild(new ExpressionStatement(assignment));
			typeDeclaration.AddChild(cd);
			
			for (int i = 0; i < typeDeclaration.Children.Count; i++) {
				object child = typeDeclaration.Children[i];
				if (child is MethodDeclaration) {
					MethodDeclaration method = (MethodDeclaration)child;
					if (method.Parameters.Count == 0 &&
					    (method.Name.StartsWith("Is") || method.Name.StartsWith("Get")))
					{
						// replace the method with a property
						PropertyDeclaration prop = new PropertyDeclaration(method.Modifier,
						                                                   method.Attributes,
						                                                   method.Name,
						                                                   null);
						prop.TypeReference = method.TypeReference;
						prop.GetRegion = new PropertyGetRegion(method.Body, null);
						typeDeclaration.Children[i] = prop;
					}
				}
			}
			
			return null;
		}
开发者ID:kingjiang,项目名称:SharpDevelopLite,代码行数:55,代码来源:WrapperGeneratorVisitor.cs

示例2: GetInitMethod

        private MethodDeclaration GetInitMethod(TypeDeclaration type)
        {
            IList methods = AstUtil.GetChildrenWithType(type, typeof(MethodDeclaration));
            string initName = "Init" + type.Name;
            foreach (MethodDeclaration methodDeclaration in methods)
            {
                if (methodDeclaration.Name == initName)
                    return methodDeclaration;
            }

            MethodDeclaration initMethod = new MethodDeclaration(initName, Modifiers.Private, new TypeReference("void"), null, null);
            initMethod.Body = new BlockStatement();
            type.AddChild(initMethod);

            return initMethod;
        }
开发者ID:sourcewarehouse,项目名称:janett,代码行数:16,代码来源:InitializerBlockTransformer.cs

示例3: ExecuteIntroduceMethod

		internal void ExecuteIntroduceMethod(UnknownMethodResolveResult rr, Ast.Expression invocationExpr, ITextEditor editor, bool isNew, object result)
		{
			IClass targetClass = IsEqualClass(rr.CallingClass, rr.Target.GetUnderlyingClass()) ? rr.CallingClass
				: rr.Target.GetUnderlyingClass();
			
			CodeGenerator gen = targetClass.ProjectContent.Language.CodeGenerator;
			IAmbience ambience = targetClass.ProjectContent.Language.GetAmbience();
			
			ClassFinder finder = new ClassFinder(rr.CallingMember);
			
			ModifierEnum modifiers = ModifierEnum.None;
			
			bool isExtension = !targetClass.IsUserCode();
			
			if (IsEqualClass(rr.CallingClass, targetClass)) {
				if (rr.CallingMember != null)
					modifiers |= (rr.CallingMember.Modifiers & ModifierEnum.Static);
			} else {
				if (isExtension) {
					if (isNew)
						targetClass = rr.CallingClass;
					else
						targetClass = result as IClass;
				}
				// exclude in Unit Test mode
				if (WorkbenchSingleton.Workbench != null)
					editor = (FileService.OpenFile(targetClass.CompilationUnit.FileName) as ITextEditorProvider).TextEditor;
				if (targetClass.ClassType != ClassType.Interface)
					modifiers |= ModifierEnum.Public;
				if (rr.IsStaticContext)
					modifiers |= ModifierEnum.Static;
			}
			
			NRefactoryResolver resolver = Extensions.CreateResolverForContext(targetClass.ProjectContent.Language, editor);
			
			IReturnType type = resolver.GetExpectedTypeFromContext(invocationExpr);
			Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, finder);
			
			if (typeRef.IsNull) {
				if (invocationExpr.Parent is Ast.ExpressionStatement)
					typeRef = new Ast.TypeReference("void", true);
				else
					typeRef = new Ast.TypeReference("object", true);
			}
			
			Ast.MethodDeclaration method = new Ast.MethodDeclaration {
				Name = rr.CallName,
				Modifier = CodeGenerator.ConvertModifier(modifiers, finder),
				TypeReference = typeRef,
				Parameters = CreateParameters(rr, finder, invocationExpr as Ast.InvocationExpression).ToList(),
			};
			
			if (targetClass.ClassType != ClassType.Interface)
				method.Body = CodeGenerator.CreateNotImplementedBlock();
			
			RefactoringDocumentAdapter documentWrapper = new RefactoringDocumentAdapter(editor.Document);
			
			if (isExtension) {
				method.Parameters.Insert(0, new Ast.ParameterDeclarationExpression(CodeGenerator.ConvertType(rr.Target, finder), "thisInstance"));
				method.IsExtensionMethod = true;
				method.Modifier |= Ast.Modifiers.Static;
			}
			
			if (isNew) {
				Ast.TypeDeclaration newType = new Ast.TypeDeclaration(isExtension ? Ast.Modifiers.Static : Ast.Modifiers.None, null);
				newType.Name = result as string;
				newType.AddChild(method);
				gen.InsertCodeAfter(targetClass, documentWrapper, newType);
			} else {
				if (IsEqualClass(rr.CallingClass, targetClass))
					gen.InsertCodeAfter(rr.CallingMember, documentWrapper, method);
				else
					gen.InsertCodeAtEnd(targetClass.BodyRegion, documentWrapper, method);
			}
			
			if (targetClass.ClassType == ClassType.Interface)
				return;
			
			ParseInformation info = ParserService.ParseFile(targetClass.CompilationUnit.FileName);
			if (info != null) {
				IMember newMember;
				
				if (isNew)
					targetClass = info.CompilationUnit.Classes.FirstOrDefault(c => c.DotNetName == c.Namespace + "." + (result as string));
				else
					targetClass = info.CompilationUnit.Classes.Flatten(c => c.InnerClasses).FirstOrDefault(c => c.DotNetName == targetClass.DotNetName);
				
				if (targetClass == null)
					return;
				
				if (IsEqualClass(rr.CallingClass, targetClass)) {
					newMember = targetClass.GetInnermostMember(editor.Caret.Line, editor.Caret.Column);
					newMember = targetClass.AllMembers
						.OrderBy(m => m.BodyRegion.BeginLine)
						.ThenBy(m2 => m2.BodyRegion.BeginColumn)
						.First(m3 => m3.BodyRegion.BeginLine > newMember.BodyRegion.BeginLine);
				} else {
					newMember = targetClass.Methods.Last();
				}
				
//.........这里部分代码省略.........
开发者ID:Rpinski,项目名称:SharpDevelop,代码行数:101,代码来源:GenerateCode.cs

示例4: AddDefaultConstructor

		/// <summary>
		/// Adds a default constructor to the type.
		/// </summary>
		protected virtual ConstructorDeclaration AddDefaultConstructor(IClass currentClass, TypeDeclaration typeDeclaration)
		{
			ConstructorDeclaration cd = new ConstructorDeclaration(typeDeclaration.Name, Modifiers.Public, null, null);
			cd.Body = new BlockStatement();
			// location is required to make Resolve() work in the constructor
			cd.StartLocation = cd.Body.StartLocation = cd.EndLocation = cd.Body.EndLocation = typeDeclaration.BodyStartLocation;
			typeDeclaration.AddChild(cd);
			if (IsAutomaticallyCallingInitializeComponent(currentClass)) {
				// the VB compiler automatically adds the InitializeComponents() call to the
				// default constructor, so the converter has to add the call when creating an explicit
				// constructor
				cd.Body.AddStatement(new IdentifierExpression("InitializeComponent").Call());
			}
			return cd;
		}
开发者ID:SiGhTfOrbACQ,项目名称:O2.Platform.Projects,代码行数:18,代码来源:VBNetToCSharpConvertVisitor.cs

示例5: GenerateInterfaceForClass

		public override string GenerateInterfaceForClass(string newInterfaceName, string existingCode, IList<IMember> membersToKeep, IClass sourceClass, bool preserveComments)
		{
			Modifiers modifiers = CodeGenerator.ConvertModifier(sourceClass.Modifiers, new ClassFinder(membersToKeep[0]));
			// keep only visibility modifiers and 'unsafe' modifier
			// -> remove abstract,sealed,static
			modifiers &= Modifiers.Visibility | Modifiers.Unsafe;
			
			TypeDeclaration interfaceDef = new TypeDeclaration(modifiers, new List<AttributeSection>());
			interfaceDef.Name = newInterfaceName;
			interfaceDef.Type = NR.Ast.ClassType.Interface;
			interfaceDef.Templates = CodeGenerator.ConvertTemplates(sourceClass.TypeParameters, new ClassFinder(membersToKeep[0]));
			
			foreach (IMember member in membersToKeep) {
				AttributedNode an = CodeGenerator.ConvertMember(member, new ClassFinder(member));
				INode node = null;
				if (an is MethodDeclaration) {
					MethodDeclaration m = an as MethodDeclaration;
					m.Body = BlockStatement.Null;
					m.Modifier = Modifiers.None;
					node = m;
				} else {
					if (an is PropertyDeclaration) {
						PropertyDeclaration p = an as PropertyDeclaration;
						p.GetRegion.Block = BlockStatement.Null;
						p.SetRegion.Block= BlockStatement.Null;
						p.Modifier = Modifiers.None;
						node = p;
					} else {
						if (an is EventDeclaration) {
							EventDeclaration e = an as EventDeclaration;
							e.Modifier = Modifiers.None;
							node = e;
						}
					}
				}
				
				if (node == null)
					throw new NotSupportedException();
				
				interfaceDef.AddChild(node);
			}
			
			IOutputAstVisitor printer = this.GetOutputVisitor();
			
			interfaceDef.AcceptVisitor(printer, null);
			
			string codeForNewInterface = printer.Text;

			// wrap the new code in the same comments/usings/namespace as the the original class file.
			string newFileContent = CreateNewFileLikeExisting(existingCode, codeForNewInterface);

			return newFileContent;
		}
开发者ID:XQuantumForceX,项目名称:Reflexil,代码行数:53,代码来源:NRefactoryRefactoringProvider.cs

示例6: InitStaticVariable

		INode InitStaticVariable(string initFieldName, string variableName, Expression initializer, TypeDeclaration typeDeclaration)
		{
			const string helperMethodName = "InitStaticVariableHelper";
			
			if (typeDeclaration != null) {
				if (!typeDeclaration.Children.OfType<MethodDeclaration>().Any(m => m.Name == helperMethodName)) {
					// add helper method
					var helperMethod = new MethodDeclaration {
						Name = helperMethodName,
						Modifier = Modifiers.Static,
						TypeReference = new TypeReference("System.Boolean", true),
						Parameters = {
							new ParameterDeclarationExpression(new TypeReference("Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag"), "flag")
						},
						Body = new BlockStatement()
					};
					BlockStatement trueBlock = new BlockStatement();
					BlockStatement elseIfBlock = new BlockStatement();
					BlockStatement falseBlock = new BlockStatement();
					helperMethod.Body.AddStatement(
						new IfElseStatement(ExpressionBuilder.Identifier("flag").Member("State").Operator(BinaryOperatorType.Equality, new PrimitiveExpression(0))) {
							TrueStatement = { trueBlock },
							ElseIfSections = {
								new ElseIfSection(ExpressionBuilder.Identifier("flag").Member("State").Operator(BinaryOperatorType.Equality, new PrimitiveExpression(2)), elseIfBlock)
							},
							FalseStatement = { falseBlock }
						});
					trueBlock.Assign(ExpressionBuilder.Identifier("flag").Member("State"), new PrimitiveExpression(2));
					trueBlock.Return(new PrimitiveExpression(true));
					elseIfBlock.Throw(new TypeReference("Microsoft.VisualBasic.CompilerServices.IncompleteInitialization").New());
					falseBlock.Return(new PrimitiveExpression(false));
					typeDeclaration.AddChild(helperMethod);
				}
			}
			
			BlockStatement tryBlock = new BlockStatement();
			BlockStatement ifTrueBlock = new BlockStatement();
			tryBlock.AddStatement(new IfElseStatement(ExpressionBuilder.Identifier(helperMethodName).Call(ExpressionBuilder.Identifier(initFieldName)), ifTrueBlock));
			ifTrueBlock.Assign(ExpressionBuilder.Identifier(variableName), initializer);
			
			BlockStatement finallyBlock = new BlockStatement();
			finallyBlock.Assign(ExpressionBuilder.Identifier(initFieldName).Member("State"), new PrimitiveExpression(1));
			
			BlockStatement lockBlock = new BlockStatement();
			lockBlock.AddStatement(new TryCatchStatement(tryBlock, null, finallyBlock));
			return new LockStatement(ExpressionBuilder.Identifier(initFieldName), lockBlock);
		}
开发者ID:XQuantumForceX,项目名称:Reflexil,代码行数:47,代码来源:ToCSharpConvertVisitor.cs

示例7: CreateParameterizedConstructor

 internal static ConstructorDeclaration CreateParameterizedConstructor(TypeDeclaration cut)
 {
     var result = new ConstructorDeclaration(cut.Name, Modifiers.Public,
         null, Parent.AbstractMethodTemplate.EmptyAttributeList);
     result.AddParameter(StringTypeReference, "name");
     cut.AddChild(result);
     return result;
 }
开发者ID:olivierdagenais,项目名称:testoriented,代码行数:8,代码来源:AbstractMethodTemplate.cs

示例8: CreateDefaultConstructor

 internal static ConstructorDeclaration CreateDefaultConstructor(TypeDeclaration cut)
 {
     var result = new ConstructorDeclaration(cut.Name, Modifiers.Public,
         Parent.AbstractMethodTemplate.EmptyParameterList, Parent.AbstractMethodTemplate.EmptyAttributeList);
     cut.AddChild(result);
     return result;
 }
开发者ID:olivierdagenais,项目名称:testoriented,代码行数:7,代码来源:AbstractMethodTemplate.cs

示例9: AddInstanceField

 private void AddInstanceField(TypeDeclaration typeDeclaration, string instanceFieldName)
 {
     FieldDeclaration newField = GetInstanceField(instanceFieldName);
     IList fields = AstUtil.GetChildrenWithType(typeDeclaration, typeof(FieldDeclaration));
     if (!ContainsField(fields, newField, true))
     {
         typeDeclaration.AddChild(newField);
         newField.Parent = typeDeclaration;
     }
 }
开发者ID:sourcewarehouse,项目名称:janett,代码行数:10,代码来源:InnerClassTransformer.cs

示例10: Parse

		// Steps to load the designer:
		// - Parse main file
		// - Find other files containing parts of the form
		// - Parse all files and look for fields (for controls) and InitializeComponents method
		// - Create CodeDom objects for fields and InitializeComponents statements
		// - If debug build and Ctrl pressed, output CodeDom to console
		// - Return CodeDom objects to the .NET designer
		protected override CodeCompileUnit Parse()
		{
			LoggingService.Debug("NRefactoryDesignerLoader.Parse()");
			
			lastTextContent = this.Generator.ViewContent.DesignerCodeFileContent;
			
			ParseInformation parseInfo = ParserService.GetParseInformation(this.Generator.ViewContent.DesignerCodeFile.FileName);
			
			IClass formClass;
			bool isFirstClassInFile;
			IList<IClass> parts = FindFormClassParts(parseInfo, out formClass, out isFirstClassInFile);
			
			const string missingReferenceMessage = "Your project is missing a reference to '${Name}' - please add it using 'Project > Add Reference'.";
			
			if (formClass.ProjectContent.GetClass("System.Drawing.Point", 0) == null) {
				throw new FormsDesignerLoadException(StringParser.Parse(missingReferenceMessage, new StringTagPair("Name", "System.Drawing")));
			}
			if (formClass.ProjectContent.GetClass("System.Windows.Forms.Form", 0) == null) {
				throw new FormsDesignerLoadException(StringParser.Parse(missingReferenceMessage, new StringTagPair("Name" , "System.Windows.Forms")));
			}
			
			List<KeyValuePair<string, CompilationUnit>> compilationUnits = new List<KeyValuePair<string, CompilationUnit>>();
			bool foundInitMethod = false;
			foreach (IClass part in parts) {
				string fileName = part.CompilationUnit.FileName;
				if (fileName == null) continue;
				bool found = false;
				foreach (KeyValuePair<string, CompilationUnit> entry in compilationUnits) {
					if (FileUtility.IsEqualFileName(fileName, entry.Key)) {
						found = true;
						break;
					}
				}
				if (found) continue;
				
				ITextBuffer fileContent;
				if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.PrimaryFileName)) {
					fileContent = this.Generator.ViewContent.PrimaryFileContent;
				} else if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.DesignerCodeFile.FileName)) {
					fileContent = new StringTextBuffer(this.Generator.ViewContent.DesignerCodeFileContent);
				} else {
					fileContent = ParserService.GetParseableFileContent(fileName);
				}
				
				ICSharpCode.NRefactory.IParser p = ICSharpCode.NRefactory.ParserFactory.CreateParser(language, fileContent.CreateReader());
				p.Parse();
				if (p.Errors.Count > 0) {
					throw new FormsDesignerLoadException("Syntax errors in " + fileName + ":\r\n" + p.Errors.ErrorOutput);
				}
				
				// Try to fix the type names to fully qualified ones
				FixTypeNames(p.CompilationUnit, part.CompilationUnit, ref foundInitMethod);
				compilationUnits.Add(new KeyValuePair<string, CompilationUnit>(fileName, p.CompilationUnit));
			}
			
			if (!foundInitMethod)
				throw new FormsDesignerLoadException("The InitializeComponent method was not found. Designer cannot be loaded.");
			
			CompilationUnit combinedCu = new CompilationUnit();
			NamespaceDeclaration nsDecl = new NamespaceDeclaration(formClass.Namespace);
			combinedCu.AddChild(nsDecl);
			TypeDeclaration formDecl = new TypeDeclaration(Modifiers.Public, null);
			nsDecl.AddChild(formDecl);
			formDecl.Name = formClass.Name;
			foreach (KeyValuePair<string, CompilationUnit> entry in compilationUnits) {
				foreach (object o in entry.Value.Children) {
					TypeDeclaration td = o as TypeDeclaration;
					if (td != null && td.Name == formDecl.Name) {
						foreach (INode node in td.Children)
							formDecl.AddChild(node);
						formDecl.BaseTypes.AddRange(td.BaseTypes);
					}
					if (o is NamespaceDeclaration) {
						foreach (object o2 in ((NamespaceDeclaration)o).Children) {
							td = o2 as TypeDeclaration;
							if (td != null && td.Name == formDecl.Name) {
								foreach (INode node in td.Children)
									formDecl.AddChild(node);
								formDecl.BaseTypes.AddRange(td.BaseTypes);
							}
						}
					}
				}
			}
			
			CodeDomVisitor visitor = new CodeDomVisitor();
			visitor.EnvironmentInformationProvider = new ICSharpCode.SharpDevelop.Dom.NRefactoryResolver.NRefactoryInformationProvider(formClass.ProjectContent);
			visitor.VisitCompilationUnit(combinedCu, null);
			
			// output generated CodeDOM to the console :
			#if DEBUG
			if ((Control.ModifierKeys & Keys.Control) == Keys.Control) {
				CodeDomVerboseOutputGenerator outputGenerator = new CodeDomVerboseOutputGenerator();
//.........这里部分代码省略.........
开发者ID:nylen,项目名称:SharpDevelop,代码行数:101,代码来源:NRefactoryDesignerLoader.cs


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