我有一个包含其他几个类的列表的类。
class OuterClass
{
IList<A> listA=new List<A>();
IList<B> listB= new List<B>();
IList<c> listC=new List<B>();
......... and so on ............
}
所有这些类(A,B,C ..)具有称为'RowState'的相同属性。 现在,我创建了两个“ OuterClass”对象
OuterClass outerClassOne = new Outerclass();
OuterClass outerClasstwo= new OuterClass();
对'outerClasstwo'执行少量操作后,我想将对象'outerClasstwo'中所有对象的'RowState'值复制到'outerClassOne'
我尝试创建泛型函数以将属性从一个对象复制到另一个对象,并且此方法已成功完成。但是我必须为每个列表调用此函数并静态传递其类型。然后,我尝试反射来获取列表名称及其类型。但是我无法将列表类型传递给函数
public void CopyRowState(OuterClass fromOrderData, OuterClass toOrderData)
{
//this work for me ,but i have to call this function for every list in my class
CopyFromList< A>(fromOrderData.listA.ToList(), toOrderData.listA.ToList());
//working code end
PropertyInfo[] classProperties = typeof(OMSOrderData).GetProperties();
foreach (PropertyInfo propertyInfo in classProperties)
{
Type type = propertyInfo.PropertyType;
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>) || interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
Type itemType = type.GetGenericArguments()[0];
//want to pass list from here
//CopyFromList<itemType.GetType()>(propertyInfo.GetValue(fromOrderData),propertyInfo.GetValue(toOrderData));
break;
}
}
}
}
private void CopyFromList<T>(List<T> from ,List<T> to)
{
if (from.Count == to.Count)
{
for(int i = 0; i < from.Count; i++)
{
Copy(from[i], to[i]);
}
}
}
private void Copy(object from, object to)
{
if (from != null && to != null)
{
string property = "RowState";
PropertyInfo propfrom = from.GetType().GetProperty(property);
var value = propfrom.GetValue(from);
PropertyInfo propertyInfoTo = to.GetType().GetProperty(property);
propertyInfoTo.SetValue(to, value);
}
}