Class A{
  private int name;
  public int Name{ get; set; }
}Class B{
  private int name;
  public int Name{ get; set; }
}
B b=new B();
怎样把B转换成A?
List<B>呢?

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using System.Linq;
    using System.Reflection;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Test t = new Test();
                B b = new B();
                b.Id = 5;            A a = t.Convert(b);            Console.WriteLine(a.Id);            Console.ReadLine();
            }
        }    public class A
        {
            public int Id { get; set; }
        }    public class B
        {
            public int Id { get; set; }
        }    public class Test
        {
            public A Convert(B b)
            {
                A a = Activator.CreateInstance<A>();            a.GetType().GetProperty("Id").SetValue(a,
                b.GetType().GetProperty("Id").GetValue(b, null), null);            return a;
            }
        }
    }
      

  2.   

    自己实现类型转换。
    public static void Test()
    {
        A o = new A();
        o.Name = 123;
        Console.WriteLine(((B)o).Name);
    }class A
    {
        private int name;
        public int Name { get; set; }
        public static explicit operator B(A o)
        {
            B o2 = new B();
            o2.Name = o.Name;
            return o2;
        }
    }class B
    {
        private int name;
        public int Name { get; set; }
        public static explicit operator A(B o)
        {
            A o2 = new A();
            o2.Name = o.Name; 
            return o2;
        }
    }