C# 两个结构相同的类进行赋值
假入两个类A类和B类不有任何继承关系,它们属性名相同,怎么给他们互相赋值呢?下面的方法就可以了。
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 itemL in propertiesL) { foreach (System.Reflection.PropertyInfo itemT in propertiesT) { if (itemL.Name == itemT.Name) { object value = itemT.GetValue(t, null); itemL.SetValue(setT, value, null); } } } return setT; }
调用(比如将A类赋值给B类):
A classA = new A(); classA.Name="test"; classA.Age="22"; B classB = new B(); classB = SetProperties<A,B>(A a);