c# 2 个结构相同的类赋值怎么做好
A类和B类不有任何继承关系,他们属性名相同,怎么给他们互相赋值呢

解决方案 »

  1.   


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

  2.   

     public bool Enabled;                                            //是否有效
            public bool Live;                                               //是否是旧数据        public int WebID;                                               //网ID
            public int Kind;                                                //数据类型(1-单独赢,2-单位置,3-两个都有)
    这样的类属性似乎不能用
      

  3.   

    namespace hardcopy
    {
        [StructLayout(LayoutKind.Sequential)]
        public class A {
            public int a;
            public A() { a = 0; }
        }
        [StructLayout(LayoutKind.Sequential)]
        public class B 
        {
            public int a;
            public B() { a = 0; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                A a1 = new A();
                a1.a = 100;
                B b1=new B();
                IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(a1));
                Marshal.StructureToPtr(a1, p, true);
                Marshal.PtrToStructure(p,b1);
            }
        }
    }