反射:(1)核心:动态操作程序集(根据元数据)
举例:
static void Main(string[] args)
{
Do(new { Id=1,Name="Hello"});
Console.ReadKey();
}
private static void Do(object p)
{
//什么是反射
//动态操作程序集(根据元数据)
var props=p.GetType().GetProperties();
foreach(var item in props)
{
Console.WriteLine(item.Name+"--"+item.GetValue(p));
}
}
namespace 反射高级用法
{
class Program
{
static void Main(string[] args)
{
using(SqlConnection connection =new SqlConnection(""))
{
using(SqlCommand command = connection.CreateCommand())
{
command.CommandText = "";
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Person p = MapEntity<Person>(reader);
}
}
}
}
}
Console.ReadKey();
}
private static T MapEntity<T>(SqlDataReader reader)where T : new()
{
var props = typeof(T).GetProperties();
var p = new T();
foreach(var prop in props)
{
if (prop.CanWrite)
{
//尝试根据属性名称获取reader中的值
//根据列名获取列序号
var index = reader.GetOrdinal(prop.Name);
//取值
var value = reader.GetValue(index);
//将值放入对象上
prop.SetValue(p, Convert.ChangeType(value, prop.PropertyType));
}
}
return p;
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}
最后
以上就是雪白钢笔最近收集整理的关于反射及反射的高级应用的全部内容,更多相关反射及反射内容请搜索靠谱客的其他文章。
发表评论 取消回复