using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace ConsoleApplication6
{
[AttributeUsage(AttributeTargets.Class,Inherited=false,AllowMultiple=false)]
public sealed class NovDBAttribute : Attribute
{
private string _tableName;
public NovDBAttribute()
{}
public NovDBAttribute(string tableName)
{
_tableName=tableName;
}
}
[AttributeUsage(AttributeTargets.Property,Inherited=false,AllowMultiple=false)]
public sealed class NovProAttribute : Attribute
{
public Type _type;
public bool _enableNull;
public string _proName;
public NovProAttribute(){}
public NovProAttribute(Type type,bool enableNull,string proName)
{
_type=type;
_enableNull=enableNull;
_proName=proName;
}
}
[NovDB("userTable")]
public class People
{
[NovPro(typeof(Int32),false,"id")]
public int ID{set;get;}
[NovPro(typeof(String), true, "name")]
public string name{set;get;}
[NovPro(typeof(String), true, "sex")]
public string sex{set;get;}
}
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable("userTable");
DataColumn idcolumn = new DataColumn("id", typeof(Int32));
DataColumn namecolumn = new DataColumn("name", typeof(String));
DataColumn sexcolumn=new DataColumn("sex",typeof(String));
table.Columns.Add(idcolumn);
table.Columns.Add(namecolumn);
table.Columns.Add(sexcolumn);
table.Rows.Add(1,"jak","man");
table.Rows.Add(1, "join", "man");
table.Rows.Add(1, "ross", "woman"); List<People> p = RomToT<People>(table);
}
/// <summary>
/// Table转化为类实例列表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table">表</param>
/// <returns></returns>
private static List<T> RomToT<T>(DataTable table) where T : class, new()
{
List<T> objList =new List<T>();
Type t = typeof(T);
object[] att = t.GetCustomAttributes(false);
PropertyInfo[] pro=t.GetProperties();
NovProAttribute[] proattributeArray = new NovProAttribute[pro.Length]; //T类属性的特性属性
for (var i = 0; i < pro.Length; ++i)
{
object[] proAtt =pro[i].GetCustomAttributes(false);
proattributeArray[i] = proAtt == null || proAtt.Count() == 0 ? null : proAtt[0] as NovProAttribute;
}
for (var i = 0; i < table.Rows.Count; ++i)
{
T obj = new T();
//????????????这里怎么把tableRow的值赋给T的属性?即怎么生成类型T的实例?
}
object retValue = "";
return retValue as List<T>;
}
}
}
如上面的例子问号处,在RomToT方法中怎么把tableRow的值赋给T类的obj的属性实例对象类ORM
T obj = new T();
Type type = obj.GetType();
foreach (PropertyInfo pi in type.GetProperties())
{
if (table.Columns.Contains(pi.Name))
pi.SetValue(obj, table.Rows[i][pi.Name]);
}
//????????????这里怎么把tableRow的值赋给T的属性?即怎么生成类型T的实例?