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