泛型和反射
地球人都知道 构建通用的功能 泛型和反射是必不可少的,然后现在很多人都用ORM实体框架+泛型也可以构建
但其内部也是通过反射实现的。
解开迷雾 见天日吧。
---c#代码
public class Boy
{
public int BoyId { get ; set ; }
public string BoyName { get ; set ; }
}
public class Girl
{
public int GirlId { get ; set ; }
public string GirlName { get ; set ; }
}
class Program
{
static IDictionary< object , object > GetList<T>() where T : class
{
Type modelType = typeof (T);
// 创建T对象
T model = (T)Activator.CreateInstance(modelType);
// T model = Activator.CreateInstance<T>();
Type t = model.GetType();
// 获取T对象的所有属性
PropertyInfo[] props = t.GetProperties();
// 将属性名称作为key,属性值作为value
Dictionary< object , object > dict = new Dictionary< object , object > ();
foreach (PropertyInfo prop in props)
{
// 获取属性的名称
string propName = prop.Name;
// 为model对象的pro属性设置值
// 如果此属性类型是int就赋值10
if (prop.PropertyType== typeof (Int32))
{ // 在实际开发中 一般用 DataRow获取数据库相应的字段值如 dr[propName]
prop.SetValue(model, 10 , null );
}
else // 如果此属性类型 不是 int就统一赋值"aaa"
{
prop.SetValue(model, " aaa " , null );
}
// 获取model中是属性值
object propValue=prop.GetValue(model, null );
dict.Add(propName,propValue.ToString());
}
return dict;
}
static void Main( string [] args)
{
foreach ( var item in GetList<Boy> ())
{
Console.WriteLine(item.Key + " : " + item.Value);
}
Console.WriteLine( " success " );
Console.ReadKey();
}
}
---运行结果
---泛型约束
http://HdhCmsTestcnblogs测试数据/zjflove/archive/2013/01/07/2849508.html
作者: Leo_wl
出处: http://HdhCmsTestcnblogs测试数据/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did47290