假入兩個類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);