繁体   English   中英

C#重写函数如何返回null

[英]C# override function how to return null

因此,我正在尝试实现一些继承,并且遇到了一个问题。 我来自Java,因此我基本上是在尝试转换代码。 因此,例如在Java中,您可能会有这个。

public class galaxyFactory extends abstractFactory
{
    @Override
    public galaxy setType()
    {   
        return new Spiral();
    }

    @Override
    SolarSystem setType() 
    {
        return null;
    }
}

如果您在一个星系之后,这将返回一个新的Spiral对象,并使用简单的return null覆盖SolarSystem setType。 但是,当尝试将其转换为C#时,我想到了类似的东西。 哪个无效,它会因“未处理NullReferenceException”而出错

  class GalaxyFactory: AbstractFactory
  {
    public override Galaxy CreateProductA()
    {
        return new spiral();
    }
    public override SolarSystem CreateProductB()
    {
        return null;
    }
  }

为了在c#中获得相同的效果,我需要更改我的return null吗?

发生此错误的原因是您尝试使用未初始化的对象。 当您通过使用CreateProductB获得SolarSystem时,实际上您会得到一个空对象,然后当您尝试使用该对象时,显然它将抛出NullReferenceException。

class GalaxyFactory: AbstractFactory
  {
    public override Galaxy CreateProductA()
    {
        return spiral();
    }
    public override SolarSystem CreateProductB()
    {
        return null;
    }
  }

null不是函数。.因此,不要在()之后加上null; 它只是空的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM