class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            B web = new B();
            web.Color = "Blue";
            C botton = new C();
            botton.Border = 1;
            p.Factory(web);
            p.Factory(botton);
            Console.ReadLine();
        }        public void Factory(A control)
        {
            
        }        public class A
        {
            public int Width;
            public int Height;
        }
        public class B : A
        {
            public string Color;
        }
        public class C : A
        {
            public int Border;
        }
    }
这样没有问题
==================================
问题是:如果把 public void Factory(A control)定义为 public void Factory(ref A control)
那么在调用派生的类时就会报错 p.Factory(ref web);
请高手指点是什么原因,怎样解决class

解决方案 »

  1.   

    方法1:
    修改Factory方法定义        public void Factory<T>(ref T control) where T : A
            {        }
    方法2:
    传参的时候使用父类引用
            static void Main(string[] args)
            {
                Class1 p = new Class1();
                B web = new B();
                web.Color = "Blue";
                A web_a = web;
                C botton = new C();
                botton.Border = 1;
                p.Factory(ref web_a);
                p.Factory(ref botton);
                Console.ReadLine();
            }
      

  2.   

    当然不可以。设想如果可以会是什么场景
    B web = new B();
    p.Factory(web);class D : A { ... }
    void Factory(ref A control)
    {
        control = new D();
    }
    相当于
    B web = new B();
    web = new D(); //你觉得这样可以么?变通的办法:
            static void Main(string[] args)
            {
                Program p = new Program();
                B web = new B();
                web.Color = "Blue";
                C botton = new C();
                botton.Border = 1;
                p.Factory(ref web);
                p.Factory(ref botton);
                Console.ReadLine();
            }        public void Factory<T>(ref T control) where T : A
            {        }
      

  3.   

    可以这样写
     var a = (A)web;
     p.Factory(ref a);