使用屬性和反射過渡從數據存取層到業務物件 - II
2024-07-21 02:23:12
供稿:網友
簡介
前面的文章我介紹了使用attributes來描述業務物件.這篇文章我將會展示如何從類中提取描述信息.為了解釋它是如何工作的,我將通過前面在類中使用的attributes寫個應用來創建sql腳本用來生成表.
工具
這是一個控制臺應用.工具將會裝載裝配件,列舉出類中標有datatable的attibute生成sql腳本用來創建表.
開始裝載部分代碼:
public static void main(string[] args)
{
if (args.length != 1)
{
console.writeline("usage: scriptgen [assembly path]");
return;
}
assembly assembly = null;
try
{
assembly = assembly.loadfrom(args[0]);
}
catch (exception e)
{
console.writeline("failed to load assembly [" + args[0] + "]");
console.writeline(e.message);
}
}
以上的代碼試圖通過參數路徑來裝載裝配件.現在我們必須列舉出所有的含有datatable attribute的裝配件.為了完成這個工作,請看如下代碼:
public void parseassembly(assembly assembly)
{
type[] types = assembly.gettypes();
foreach(type type in types)
{
if (type.isclass)
{
datatableattribute[] datatable = (datatableattribute[])
type.getcustomattributes(typeof(datatableattribute),
true);
if (datatable.length > 0)
{
console.writeline("found class '{0}'", type.tostring());
}
}
}
}
以下是列舉屬性的代碼.
void parseclass(type type, datatableattribute datatable)
{
propertyinfo[] properties = type.getproperties();
// gets the key field
foreach (propertyinfo property in properties)
{
keyfieldattribute[] key = (keyfieldattribute[])
property.getcustomattributes(typeof(keyfieldattribute),
true);
if (key.length > 0)
{
console.writeline("key = " + property.name + " type is "
+ property.propertytype);
break;
}
}
// gets the other fields
foreach (propertyinfo property in properties)
{
basefieldattribute[] field = (basefieldattribute[])
property.getcustomattributes(typeof(basefieldattribute),
true);
if (field.length > 0)
{
if (!(field[0] is keyfieldattribute))
{
console.writeline("property " + property.name
+ " [" + property.propertytype + "] " +
+ "maps to column [
+ field[0].columnname + "]");
}
}
}
}
現在我們不得不創建sql腳本.我們的工具僅能滿足2個需求: key是int,identify 屬性類型只有這些是允許的:string,int,decimal,和datetime.
源文件將會創建以下的裝配件:
dal.dll: 包含 attributes
customer.dll: 包含業務物件
scriptgen.exe: 用來生成sql腳本的工具.
下一步
接下來的文章我將創建整個dal,用來在運行時間得到物件等等.