日期:2014-05-18  浏览次数:21022 次

c# 创建类(.cs)
不用Stream创建
有没有其他的,比如创建xml有xmlDocument 这样可以有相对的格式,创建.cs文件有没有相关的对象?

------解决方案--------------------
System.CodeDom


内容可能太短。。。
------解决方案--------------------
??
动态创建类
???
和你cs文件有何关系,cs是输出,类是运行期??

如果要动态创建,运行期类,参考codedom
如果要输出cs文件,参考Microsoft.CSharp.CSharpCodeProvider类
------解决方案--------------------
LZ是不是要生成一个cs文件阿?但又要像自己在VS里写的那样自动缩进?
------解决方案--------------------
楼主是想根据类图之类的东西生成.cs文件吧
CodeDom
------解决方案--------------------
不知道lz的意思是否是这样
http://www.dotnetspider.com/resources/565-Generating-C-Class-File-Sample-cs-Dynamically-us.aspx
------解决方案--------------------
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Text;
using System.Reflection;

namespace ADOGuy
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Evaluator
{
#region Construction
public Evaluator(EvaluatorItem[] items)
{
ConstructEvaluator(items);
}

public Evaluator(Type returnType, string expression, string name)
{
EvaluatorItem[] items = { new EvaluatorItem(returnType, expression, name) };
ConstructEvaluator(items);
}

public Evaluator(EvaluatorItem item)
{
EvaluatorItem[] items = { item };
ConstructEvaluator(items);
}

private void ConstructEvaluator(EvaluatorItem[] items)
{
ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.xml.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;

StringBuilder code = new StringBuilder();
code.Append("using System; \n");
code.Append("using System.Data; \n");
code.Append("using System.Data.SqlClient; \n");
code.Append("using System.Data.OleDb; \n");
code.Append("using System.Xml; \n");
code.Append("namespace ADOGuy { \n");
code.Append(" public class _Evaluator { \n");
foreach(EvaluatorItem item in items)
{
code.AppendFormat(" public {0} {1}() ",
item.ReturnType.Name,
item.Name);
code.Append("{ ");
code.AppendFormat(" return ({0}); ", item.Expression);
code.Append("}\n");
}
code.Append("} }");

CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString());
if (cr.Errors.HasErrors)
{
StringBuilder error = new StringBuilder();
error.Append("Error Compiling Expression: ");
foreach (CompilerError err in cr.Errors)
{
error.AppendFormat("{0}\n", err.ErrorText);
}
throw new Exception("Error Compiling Expression: " + error.ToString());
}
Assembly a = cr.CompiledAssembly;
_Compiled = a.CreateInstance("ADOGuy._Evaluator");
} #endregion

#region Public Members
public int EvaluateInt(string name)