在工作中遇到两个类具有相同的属性,但是是不同的两个类,属性很多,互相转换起来很麻烦,于是就想到了下面的办法,实现他们的互相转换,请指教:
public static List<T2> ConvertT1ToT2<T1, T2>(List<T1> resouceList) where T1 : new() where T2 : new()
{
T1 resouce = new T1();
T2 target = new T2();
List<T2> targetList = new List<T2>();
PropertyInfo[] resoucePropinfos = null;
PropertyInfo[] targetPropinfos = null;
if (resoucePropinfos == null)
{
Type objtype = resouce.GetType();
resoucePropinfos = objtype.GetProperties();
}
if (targetPropinfos == null)
{
Type objtype = target.GetType();
targetPropinfos = objtype.GetProperties();
}
foreach (T1 t1 in resouceList)
{
Hashtable resouceHashtable = new Hashtable();
T2 tempTarget = new T2();
foreach (PropertyInfo property in resoucePropinfos)
{
resouceHashtable.Add(property.Name, property.GetValue(t1, null));
}
foreach (PropertyInfo property in targetPropinfos)
{
property.SetValue(tempTarget, SetType(resouceHashtable[property.Name], property.PropertyType), null);
} targetList.Add(tempTarget);
} return targetList;
}
public static object SetType(this object value, Type conversionType)
{
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value != "" && value != null)
{
NullableConverter nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
else
{
return null;
}
}
return System.Convert.ChangeType(value, conversionType);
}
调用实例:
public class A1 {
public string a1 { get; set; }
public string a2 { get; set; }
public A1(string a1, string a2)
{
this.a1 = a1;
this.a2 = a2;
}
public A1() { }
}
public class B1
{
public string a1 { get; set; }
public int a2 { get; set; }
public string a3 { get; set; }
public B1(string a1, int a2)
{
this.a1 = a1;
this.a2 = a2;
}
public B1() { }
}
List<A1> list1 = new List<A1>();
A1 a1 = new A1();
a1.a1 = "11";
a1.a2 = "12";
list1.Add(a1);
A1 a2 = new A1();
a2.a1 = "21";
a2.a2 = "22";
list1.Add(a2);
A1 a3 = new A1();
a3.a1 = "31";
a3.a2 = "32";
list1.Add(a3);
B1 b1 = new B1();
List<B1> Listb2 = ConvertT1ToT2<A1, B1>(list1);