【问题标题】:Function polymorphism. Return B as A is null when A:B函数多态。当 A:B 时返回 B,因为 A 为空
【发布时间】:2012-05-09 23:47:47
【问题描述】:

如何执行以下操作?
我的A 对象在调用GetB 后为空,即使A 继承自B

class Program
{
    public class A : B
    {
    }

    public class B
    {
    }

    static void Main(string[] args)
    {
        A a = GetB() as A;
        Console.WriteLine(a == null); // it is null!

        Console.WriteLine("Console.ReadKey();");
        Console.ReadKey();
    }
    public static B GetB()
    {
        return new B();
    }
}

【问题讨论】:

  • C 类:B { }。 C是A吗?显然不是。怎么会这样?那么,为什么您认为应该能够将 any B 转换为 A? A继承B,而不是相反。 A 是 B,这很清楚。乙?可能是 C. D. 也可能只是普通的旧 B。
  • @AnthonyPegram 在下面看到我的回答,我们想得太像了......
  • 错误是more pronounced,如果你做旧风格的铸造。即A a = (A)GetB()

标签: c# inheritance polymorphism


【解决方案1】:

您可能指的是函数中的return new A();。目前,您正尝试将您的 B 向下转换为 A,但这是行不通的。

【讨论】:

    【解决方案2】:

    你试图将你的 B 向下转换为 A。你不能这样做,也没有意义,因为我们不知道 B 是否会成为 A。最好构建一个构造函数在您的 A 类中,该类将 B 作为参数。

    public class A : B
    {
        public A(B b)
        {
            //perform your conversion of a B into an A
        }
    }
    
    public class B
    {
        public B(){}
    }
    
    static void Main(string[] args)
    {
        B b = new B();
        A a = new A(b);
        Console.WriteLine(a == null); // it is null!
    
        Console.WriteLine("Console.ReadKey();");
        Console.ReadKey();
    }
    

    【讨论】:

      【解决方案3】:

      您将无法执行这种类型的转换,因为B 很可能不是A!当然,AB 的子类,因此您始终可以执行GetA() as B;。但是走另一条路是没有意义的。很可能A 的实例比B 的实例提供了一些额外的功能。

      考虑添加第三个类,C : B。如果您的函数GetB() 实际上返回了new C() 怎么办?这很好,因为CB。但是您肯定不想将其转换为AAC 几乎肯定没有什么共同点。

      【讨论】:

        【解决方案4】:

        你搞错了:

        class Program
        {
            public class A : B  // should be: public class A
            {
            }
        
            public class B // should be: public class B : A
            {
            }
        
            static void Main(string[] args)
            {
                // If you reverse the inheritance on code above
                // As Ben Voigt noticed, *as A* is redundant. should be removed
                // A a = GetB() as A; 
        
                // should be this. B is wider than A, so A can accept B, no need to cast
                A a = GetB(); 
                Console.WriteLine(a == null); // it is null!
        
                Console.WriteLine("Console.ReadKey();");
                Console.ReadKey();
            }
            public static B GetB()
            {
                return new B();
            }
        }
        

        【讨论】:

        • 在这种情况下你根本不需要as
        • 我复制粘贴了他的代码并突出显示了错误的主要原因
        猜你喜欢
        • 2015-11-22
        • 2013-05-29
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 2021-11-28
        相关资源
        最近更新 更多