假如一个类
namespace test.dal{
public class ArticleDAL{
//根据新闻id取得一个实体对象
public GetArticleById(int id) {
test.model article=new test.model.article(); //实体化一个article对象
SqlDataReader sr=....//取数据对象
.....
article.Title=sr["title"];
article.Content=sr["content"];
......................一大堆的字段值
}
}
}这种方式,我知道可以用反射的方式简化操作,但是我不知道该怎么写,没有一点思路,请高手指点.非常谢谢!
namespace test.dal{
public class ArticleDAL{
//根据新闻id取得一个实体对象
public GetArticleById(int id) {
test.model article=new test.model.article(); //实体化一个article对象
SqlDataReader sr=....//取数据对象
.....
article.Title=sr["title"];
article.Content=sr["content"];
......................一大堆的字段值
}
}
}这种方式,我知道可以用反射的方式简化操作,但是我不知道该怎么写,没有一点思路,请高手指点.非常谢谢!
是实体类的填充还是获取DataReader对象?看不出你这个方法体内有需要发射的地方。
象一般的查询数据出来的时候
article.title=sr["title];
如果有几个字段,倒无所谓,可是有一大堆字段的时候,手写很容易出错的.
/* 反射简单示例
* 动态创建类的实例,
* 根据名称创建类的实例,
* 结合多态使用可以轻易实现插件机制
*/
class RuningTimeCreateObjectDemo
{
public static object CreateObject(string sTypeName)
{
Type type = Type.GetType(sTypeName);
object obj = Activator.CreateInstance(type);
return obj;
}
}
/*
* 下面例子中, ChangeValue类的myValue本是私有字段,
* 一般情况下在类外部是不能改它的值的, 但利用反射就能改了
*/
class ChangeValue
{
private string myValue;
public ChangeValue(string str)
{
myValue = str;
} public void WriteLine()
{
Console.WriteLine("MyValue is: " + myValue);
} public void PingPong()
{
Console.WriteLine("世乒赛男团必胜!");
}
} class Test
{
public static void ChangeValue()
{
//通过反射获取并修改字段
ChangeValue cv = new ChangeValue("old value");
cv.WriteLine(); Type t = ((object)cv).GetType();
FieldInfo field = t.GetField("myValue",
BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(cv, "new value"); cv.WriteLine(); //通过反射调用公共方法
MethodInfo method = t.GetMethod("PingPong");
method.Invoke(cv, null);
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using System.Data.SqlClient;public partial class testt : System.Web.UI.Page
{
protected OMP.BLL.ArticleBLL bll = new OMP.BLL.ArticleBLL();
protected void Page_Load(object sender, EventArgs e)
{
int recordcount = 0;
DataSet ds = bll.GetArticles(1, 1, "", out recordcount);
FillDataset(ds);
} protected void FillDataset(DataSet ds)
{
Response.Write(ds.Tables[0].Rows.Count);
Type t = typeof(OMP.Model.Article);
foreach (PropertyInfo f in t.GetProperties()) {
f.setValue(,,)///不知道怎么写.
}
}
}
这个地方,我就不知道怎么set值了,帅哥,能不能再指点一番啊,谢谢.
{
//fast reflection
if (!PropCache.Keys.Contains(p))
{
lock (syncRoot)
{
if (!PropCache.Keys.Contains(p))
{
PropCache.Add(p, EmitHelper.GetPropertySetter(p));
}
}
}
PropCache[p](obj, Convert.ChangeType(dr[p.Name], p.PropertyType)); //overtime test.
//setter = EmitHelper.GetPropertySetter(p);
////setter(obj, DTO(dr[p.Name], p.PropertyType)); //default reflection
//p.SetValue(obj, Convert.ChangeType(dr[p.Name], p.PropertyType), null);
}