⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 codegenerator.cs

📁 SharpDevelop2.0.0 c#开发免费工具
💻 CS
📖 第 1 页 / 共 2 页
字号:
		protected void InsertCodeAfter(int insertLine, IDocument document, string indentation, bool startWithEmptyLine, params AbstractNode[] nodes)
		{
			// insert one line below field (text editor uses different coordinates)
			LineSegment lineSegment = document.GetLineSegment(insertLine);
			StringBuilder b = new StringBuilder();
			for (int i = 0; i < nodes.Length; i++) {
				if (startWithEmptyLine || i > 0)
					b.AppendLine(indentation);
				b.Append(GenerateCode(nodes[i], indentation));
			}
			document.Insert(lineSegment.Offset, b.ToString());
			document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
			document.CommitUpdate();
		}
		
		/// <summary>
		/// Generates code for the NRefactory node.
		/// </summary>
		public abstract string GenerateCode(AbstractNode node, string indentation);
		#endregion
		
		#region Generate property
		public virtual string GetPropertyName(string fieldName)
		{
			if (fieldName.StartsWith("_") && fieldName.Length > 1)
				return Char.ToUpper(fieldName[1]) + fieldName.Substring(2);
			else if (fieldName.StartsWith("m_") && fieldName.Length > 2)
				return Char.ToUpper(fieldName[2]) + fieldName.Substring(3);
			else
				return Char.ToUpper(fieldName[0]) + fieldName.Substring(1);
		}
		
		public virtual string GetParameterName(string fieldName)
		{
			if (fieldName.StartsWith("_") && fieldName.Length > 1)
				return Char.ToLower(fieldName[1]) + fieldName.Substring(2);
			else if (fieldName.StartsWith("m_") && fieldName.Length > 2)
				return Char.ToLower(fieldName[2]) + fieldName.Substring(3);
			else
				return Char.ToLower(fieldName[0]) + fieldName.Substring(1);
		}
		
		public virtual PropertyDeclaration CreateProperty(IField field, bool createGetter, bool createSetter)
		{
			string name = GetPropertyName(field.Name);
			PropertyDeclaration property = new PropertyDeclaration(name,
			                                                       ConvertType(field.ReturnType, new ClassFinder(field)),
			                                                       ConvertModifier(field.Modifiers), null);
			if (createGetter) {
				BlockStatement block = new BlockStatement();
				block.AddChild(new ReturnStatement(new IdentifierExpression(field.Name)));
				property.GetRegion = new PropertyGetRegion(block, null);
			}
			if (createSetter) {
				BlockStatement block = new BlockStatement();
				Expression left = new IdentifierExpression(field.Name);
				Expression right = new IdentifierExpression("value");
				block.AddChild(new StatementExpression(new AssignmentExpression(left, AssignmentOperatorType.Assign, right)));
				property.SetRegion = new PropertySetRegion(block, null);
			}
			
			property.Modifier = Modifier.Public | (property.Modifier & Modifier.Static);
			return property;
		}
		#endregion
		
		#region Generate Changed Event
		public virtual void CreateChangedEvent(IProperty property, IDocument document)
		{
			string name = property.Name + "Changed";
			EventDeclaration ed = new EventDeclaration(new TypeReference("EventHandler"), name,
			                                           ConvertModifier(property.Modifiers & (ModifierEnum.VisibilityMask | ModifierEnum.Static))
			                                           , null, null);
			InsertCodeAfter(property, document, ed);
			
			List<Expression> arguments = new List<Expression>(2);
			if (property.IsStatic)
				arguments.Add(new PrimitiveExpression(null, "null"));
			else
				arguments.Add(new ThisReferenceExpression());
			arguments.Add(new FieldReferenceExpression(new IdentifierExpression("EventArgs"), "Empty"));
			InsertCodeAtEnd(property.SetterRegion, document,
			                new RaiseEventStatement(name, arguments));
		}
		#endregion
		
		#region Generate OnEventMethod
		public virtual MethodDeclaration CreateOnEventMethod(IEvent e)
		{
			ClassFinder context = new ClassFinder(e);
			List<ParameterDeclarationExpression> parameters = new List<ParameterDeclarationExpression>();
			bool sender = false;
			if (e.ReturnType != null) {
				IMethod invoke = e.ReturnType.GetMethods().Find(delegate(IMethod m) { return m.Name=="Invoke"; });
				if (invoke != null) {
					foreach (IParameter param in invoke.Parameters) {
						parameters.Add(new ParameterDeclarationExpression(ConvertType(param.ReturnType, context), param.Name));
					}
					if (parameters.Count > 0 && string.Equals(parameters[0].ParameterName, "sender", StringComparison.InvariantCultureIgnoreCase)) {
						sender = true;
						parameters.RemoveAt(0);
					}
				}
			}
			
			ModifierEnum modifier;
			if (e.IsStatic)
				modifier = ModifierEnum.Private | ModifierEnum.Static;
			else if (e.DeclaringType.IsSealed)
				modifier = ModifierEnum.Protected;
			else
				modifier = ModifierEnum.Protected | ModifierEnum.Virtual;
			MethodDeclaration method = new MethodDeclaration("On" + e.Name,
			                                                 ConvertModifier(modifier),
			                                                 new TypeReference("System.Void"),
			                                                 parameters, null);
			
			List<Expression> arguments = new List<Expression>();
			if (sender) {
				if (e.IsStatic)
					arguments.Add(new PrimitiveExpression(null, "null"));
				else
					arguments.Add(new ThisReferenceExpression());
			}
			foreach (ParameterDeclarationExpression param in parameters) {
				arguments.Add(new IdentifierExpression(param.ParameterName));
			}
			method.Body = new BlockStatement();
			method.Body.AddChild(new RaiseEventStatement(e.Name, arguments));
			
			return method;
		}
		#endregion
		
		#region Interface implementation
		protected string GetInterfaceName(IReturnType interf, IMember member, ClassFinder context)
		{
			if (CanUseShortTypeName(member.DeclaringType.DefaultReturnType, context))
				return member.DeclaringType.Name;
			else
				return member.DeclaringType.FullyQualifiedName;
		}
		
		public void ImplementInterface(IReturnType interf, IDocument document, bool explicitImpl, ModifierEnum implModifier, IClass targetClass)
		{
			List<AbstractNode> nodes = new List<AbstractNode>();
			ImplementInterface(nodes, interf, explicitImpl, implModifier, targetClass);
			InsertCodeAtEnd(targetClass.Region, document, nodes.ToArray());
		}
		
		/// <summary>
		/// Adds the methods implementing the <paramref name="interf"/> to the list
		/// <paramref name="nodes"/>.
		/// </summary>
		public virtual void ImplementInterface(IList<AbstractNode> nodes, IReturnType interf, bool explicitImpl, ModifierEnum implModifier, IClass targetClass)
		{
			ClassFinder context = new ClassFinder(targetClass, targetClass.Region.BeginLine + 1, 0);
			TypeReference interfaceReference = ConvertType(interf, context);
			Modifier modifier = ConvertModifier(implModifier);
			List<IEvent> targetClassEvents = targetClass.DefaultReturnType.GetEvents();
			foreach (IEvent e in interf.GetEvents()) {
				if (targetClassEvents.Find(delegate(IEvent te) { return e.Name == te.Name; }) == null) {
					EventDeclaration ed = ConvertMember(e, context);
					if (explicitImpl) {
						ed.InterfaceImplementations.Add(new InterfaceImplementation(interfaceReference, ed.Name));
					}
					ed.Modifier = modifier;
					nodes.Add(ed);
				}
			}
			List<IProperty> targetClassProperties = targetClass.DefaultReturnType.GetProperties();
			foreach (IProperty p in interf.GetProperties()) {
				if (targetClassProperties.Find(delegate(IProperty tp) { return p.Name == tp.Name; }) == null) {
					AttributedNode pd = ConvertMember(p, context);
					if (explicitImpl) {
						InterfaceImplementation impl = new InterfaceImplementation(interfaceReference, p.Name);
						if (pd is IndexerDeclaration) {
							((IndexerDeclaration)pd).InterfaceImplementations.Add(impl);
						} else {
							((PropertyDeclaration)pd).InterfaceImplementations.Add(impl);
						}
					}
					pd.Modifier = modifier;
					nodes.Add(pd);
				}
			}
			List<IMethod> targetClassMethods = targetClass.DefaultReturnType.GetMethods();
			foreach (IMethod m in interf.GetMethods()) {
				if (targetClassMethods.Find(delegate(IMethod mp) {
				                            	return m.Name == mp.Name && DiffUtility.Compare(m.Parameters, mp.Parameters) == 0;
				                            }) == null)
				{
					MethodDeclaration md = ConvertMember(m, context) as MethodDeclaration;
					if (md != null) {
						if (explicitImpl) {
							md.InterfaceImplementations.Add(new InterfaceImplementation(interfaceReference, md.Name));
						}
						md.Modifier = modifier;
						nodes.Add(md);
					}
				}
			}
		}
		#endregion
		
		#region Override member
		public virtual AttributedNode GetOverridingMethod(IMember baseMember, ClassFinder targetContext)
		{
			AttributedNode node = ConvertMember(baseMember, targetContext);
			node.Modifier &= ~(Modifier.Virtual | Modifier.Abstract);
			node.Modifier |= Modifier.Override;
			
			MethodDeclaration method = node as MethodDeclaration;
			if (method != null) {
				method.Body.Children.Clear();
				if (method.TypeReference.SystemType == "System.Void") {
					method.Body.AddChild(new StatementExpression(CreateForwardingMethodCall(method)));
				} else {
					method.Body.AddChild(new ReturnStatement(CreateForwardingMethodCall(method)));
				}
			}
			PropertyDeclaration property = node as PropertyDeclaration;
			if (property != null) {
				Expression field = new FieldReferenceExpression(new BaseReferenceExpression(),
				                                                property.Name);
				if (!property.GetRegion.Block.IsNull) {
					property.GetRegion.Block.Children.Clear();
					property.GetRegion.Block.AddChild(new ReturnStatement(field));
				}
				if (!property.SetRegion.Block.IsNull) {
					property.SetRegion.Block.Children.Clear();
					Expression expr = new AssignmentExpression(field,
					                                           AssignmentOperatorType.Assign,
					                                           new IdentifierExpression("value"));
					property.SetRegion.Block.AddChild(new StatementExpression(expr));
				}
			}
			return node;
		}
		
		static InvocationExpression CreateForwardingMethodCall(MethodDeclaration method)
		{
			Expression methodName = new FieldReferenceExpression(new BaseReferenceExpression(),
			                                                     method.Name);
			InvocationExpression ie = new InvocationExpression(methodName, null);
			foreach (ParameterDeclarationExpression param in method.Parameters) {
				Expression expr = new IdentifierExpression(param.ParameterName);
				if (param.ParamModifier == ParamModifier.Ref) {
					expr = new DirectionExpression(FieldDirection.Ref, expr);
				} else if (param.ParamModifier == ParamModifier.Out) {
					expr = new DirectionExpression(FieldDirection.Out, expr);
				}
				ie.Arguments.Add(expr);
			}
			return ie;
		}
		#endregion
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -