如何使用c#语言在运行时生成c#代码

编程入门 行业动态 更新时间:2024-10-28 02:34:55
本文介绍了如何使用c#语言在运行时生成c#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

public void AddConstructor() { Con = 此 .VarValue; // 声明构造函数 CodeConstructor构造函数= new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Parameters.Add( new CodeParameterDeclarationExpression(Type,Con)); CodeFieldReferenceExpression widthReference = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(),Con); constructor.Statements.Add( new CodeAssignStatement(widthReference, new CodeArgumentReferenceExpression( CON))); targetClass.Members.Add(constructor); }

此代码的输出为 public MyCode( String val) { this .val = val; }

i只需要非参数化的构造函数 就像这样

public MyCode() { val = Value; }

i尝试但没有得到....请给我任何简单的线索来生成c#源代码文件在运行时使用c#...

解决方案

请参阅以下链接获取类似文章:
  • 运行代码生成I:使用Microsoft编译C#代码。 CSharp和System.CodeCom.Compiler [ ^ ]
  • 动态源代码生成和编译 [ ^ ]
  • 从CodeDOM图生成和编译源代码 [ ^ ]
- Amit

public void AddConstructor() { Con = this.VarValue; // Declare the constructor CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; constructor.Parameters.Add(new CodeParameterDeclarationExpression(Type, Con)); CodeFieldReferenceExpression widthReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), Con); constructor.Statements.Add(new CodeAssignStatement(widthReference, new CodeArgumentReferenceExpression(Con))); targetClass.Members.Add(constructor); }

Output of this code is

public MyCode(String val) { this.val = val; }

i want only non parameterized Constructor like this

public MyCode() { val = "Value"; }

i tried but didn't get.... plese give me any simple clue to generate c# source code file At runtime using c#...

解决方案

Refer the links below for similar articles:
  • Run-Time Code Generation I: Compile C#-Code using Microsoft.CSharp and System.CodeCom.Compiler[^]
  • Dynamic Source Code Generation and Compilation[^]
  • Generating and Compiling Source Code from a CodeDOM Graph[^]
--Amit

更多推荐

如何使用c#语言在运行时生成c#代码

本文发布于:2023-11-09 20:10:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573308.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   语言   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!