子类、父类互相赋值的解决办法
最近写东西遇到这么个问题,A为基类,B继承A并做了扩展
数据获取时只能得到A,但是需要用B来显示数据~
现在就需要把A所有的属性赋值给B~
第一想法就是把迭代A的属性,全部赋值给B~
本着能懒就懒的原则~ Google了一下~ 真让我找到了~ 不过有些小问题~
加工了一下~
使用范例
A a = null; B b = null; a = manager.Get();//假设这里给A赋值了~ b = SetProperties<A,B>(a);
public L SetProperties<T, L>(T t) where L : new()
{
if (t == null)
{
return default(L);
}
System.Reflection.PropertyInfo[] propertiesT = typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
System.Reflection.PropertyInfo[] propertiesL = typeof(L).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
//if (propertiesT.Length != propertiesL.Length || propertiesL.Length == 0)
//{
// return default(L);
//}
L setT = new L();
foreach (System.Reflection.PropertyInfo itemT in propertiesT)
{
foreach (System.Reflection.PropertyInfo itemL in propertiesL)
{
if (itemL.Name == itemT.Name)
{
object value = itemT.GetValue(t, null);
itemL.SetValue(setT, value, null);
}
}
}
return setT;
}
你可以调整下foreach的次序来控制以A或者B的属性为基准~


