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);

 

引用:http://bbs.csdn.net/topics/360163250


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM