当前位置:编程学习 > C#/ASP.NET >>

派生类为什么加 ref 就传不了呢

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 --------------------编程问答-------------------- class不需要ref --------------------编程问答-------------------- 方法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();
        } --------------------编程问答-------------------- 当然不可以。

设想如果可以会是什么场景
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
        {

        }
--------------------编程问答-------------------- 可以,做强制类型转换就可以, --------------------编程问答-------------------- 可以这样写
 var a = (A)web;
 p.Factory(ref a);
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,