ServParam2ClientModelEngine/CoderEngine/CSharpCodeWrite.cs
2018-10-18 07:00:43 +08:00

111 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CoderEngine
{
public class CSharpCodeWrite
{
private string CodeStr = "";
/// <summary>
/// 一个代码缩进
/// </summary>
private string tabstr = " ";
/// <summary>
/// 逐行添加代码
/// </summary>
/// <param name="codeline"></param>
/// <returns></returns>
public void CoderAddLine(string CodeLine)
{
CodeStr += CodeLine + "\n";
}
public string ModelToJavaCode(string _AssemblyName, string _TypeName)
{
TypeMode tm = new _ModleReader().ModelCheck(_AssemblyName, _TypeName);
ModelToCSCodeWriter(tm);
return CodeStr;
}
public void ModelToCSCodeWriter(TypeMode TopMode)
{
//如果有代码嵌套的下级类 在本类外 写入新的类
if (TopMode.TypeList != null && TopMode.TypeList.Count > 0)
{
CoderAddLine(tabstr);
CSCodeDownRecursion(TopMode);
}
}
public void CSCodeDownRecursion(TypeMode TopMode)
{
string ClassName = "";
//如果自己就是集合类型 则取类型下名字
if (TopMode.MemberType.Name == "List`1")
{
//FullName的值为 "System.Collections.Generic.List`1[[ --集合内嵌类型名称--, CoderEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"
//其中包含内嵌List的名称 我们要将其取出 得到的值例如 “程序集.*.*类型”
var SonParamName = TopMode.MemberType.FullName.Substring(TopMode.MemberType.FullName.IndexOf("[") + 2);
SonParamName = SonParamName.Substring(0, SonParamName.IndexOf(","));
ClassName = SonParamName.Substring(SonParamName.LastIndexOf(".") + 1);
}
else
ClassName = TopMode.MemberType.Name;
CoderAddLine("public class " + ClassName + " {");
foreach (var tl in TopMode.TypeList)
{
CoderAddLine(tabstr + "public " + ToTypeName(tl.MemberType) + " " + tl.Name + " { get; set; };");
}
CoderAddLine("}");
foreach (var tl in TopMode.TypeList)
{
if (tl.MemberType.Name == "List`1")
{
if (tl.TypeList != null && tl.TypeList.Count > 0)
{
CoderAddLine("");
ModelToCSCodeWriter(tl);
}
}
}
}
/// <summary>
/// 类型处理
/// </summary>
/// <returns></returns>
public string ToTypeName(Type myType)
{
if (myType.Name == "List`1")
{
var SonParamName = myType.FullName.Substring(myType.FullName.IndexOf("[") + 2);
SonParamName = SonParamName.Substring(0, SonParamName.IndexOf(","));
return "List<" + SonParamName.Substring(SonParamName.LastIndexOf('.') + 1) + ">";
}
else if (myType.Name == "Nullable`1")
{
var SonParamName = myType.FullName.Substring(myType.FullName.IndexOf("[") + 2);
SonParamName = SonParamName.Substring(0, SonParamName.IndexOf(","));
return "Nullable<" + SonParamName.Substring(SonParamName.LastIndexOf('.') + 1) + ">";
}
else
return myType.Name;
}
}
}