版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Asa_Jim/article/details/47192979
作为程序猿免不了要搞一些根据第三方接口,页面视图模型,数据转换对象 等的繁琐写class 的工作,所以做了个特地根据现有的dll 去生成指定类的public 属性的功能,当然你也可以扩展下实现生成方法的功能。 代码很短小新建一个控制台程序就能用了
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MakeClassScript
{
class Program
{
static void Main(string[] args)
{
string dll = @"K:\xxx.Domain.dll";
string className = "BusinessDepartMent";
LoadClass(dll,className);
}
/// <summary>
///装载dll
/// </summary>
public static void LoadClass(string dllPath,string className)
{
if (dllPath == null)
return;
Assembly assembly = Assembly.LoadFrom(dllPath);
var typeList = assembly.GetTypes().Where(x => x.FullName == className); //稍微修改下就会生成所有的class
List<Type> TypeList = new List<Type>();
if (typeList == null)
return;
else
TypeList.AddRange(typeList);
string content = string.Empty;
foreach (var item in TypeList.FindAll(x => x.IsClass == true))
{
content = GetSelfProperties(item);
MakeScript(item,content);
}
//获得本类所有非进程共有属性列表
}
/// <summary>
/// da
/// </summary>
/// <param name="classType"></param>
/// <param name="content"></param>
private static void MakeScript(Type classType,string content)
{
string head = " public class " + classType.Name + Environment.NewLine;
string top = "{";
string bottom = Environment.NewLine + "}";
string Base = Environment.CurrentDirectory + @"\" + classType.Name + ".cs";
File.WriteAllText(Base,head+top+content+bottom);
}
/// <summary>
/// 获得当前类中自定义属性
/// </summary>
/// <param name="type"></param>
private static string GetSelfProperties(Type type)
{
var SelfPropertyList = type.GetProperties(BindingFlags.Public
| BindingFlags.Instance | BindingFlags.DeclaredOnly)
.ToList().FindAll(x => x.MemberType == MemberTypes.Property);
if (SelfPropertyList == null)
return "";
StringBuilder str = new StringBuilder();
foreach (var item in SelfPropertyList)
{
var s = " public " + item.PropertyType.Name + " " + item.Name + " { get;set; }";
str.Append(Environment.NewLine);
str.Append(s);
str.Append(Environment.NewLine);
}
return str.ToString();
}
}
}
因为目前我够用了,所以没有改成可以识别 父类,等的各种复杂结构,有兴趣的自己去改吧