At work, two classes have the same attributes, but they are two different classes. There are many attributes and it is very difficult to convert each other. So I came up with the following method, to achieve mutual conversion, please advise:
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 );
}
Call instance:
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 );