具有输出参数的构造函数 [英] Constructor with output-parameter

查看:226
本文介绍了具有输出参数的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我看到一个剪辑,看起来真的很可怕,但不幸的是我不能简单地改变它,所以我想知道我是否可以绕过这个不知何故。我有一个类的构造函数有一个输出参数为成功。但这看起来真的很丑的我。而现在当从这个类派生时,我必须带这个参数 - 如果我想要或不。

  class ClassA {
ClassA(out bool success){...}
}

class B:ClassA {
//从ClassA调用构造函数但没有out-param
}

所以我知道它的良好做法或者如果不是我可以避免从ClassB声明out-param。

好了,这个类的设计被打破了,所以让我们再多说一下(注意我不推荐这种方法!):

  void Main()
{

}

public class ClassA
{
public ClassA(out bool success)
{
success = true;
}
}

public class B:ClassA
{
private static bool success;

//从ClassA调用构造函数,但没有out-param
public B()
:base(out success)
{
} $除此之外,你可以得到的最接近的是一个工厂方法:

p>

  public class B:ClassA 
{
public static B Create()
{
bool成功;
var result = new B(out success);
if(success)
return result;
// TODO:Dispose result?
throw new StupidProgrammerException();
}
}


today I saw a snipped that looked really horrible to me, but unfortunetly I cannot simply change it, so I wonder if I can bypass this somehow. I have a class with a constructor that has an output-parameter for success. But that looks really ugly to me. And now when deriving from this class I have to take this param with me- if I want to or not.

class ClassA {
    ClassA(out bool success) {...}
}

class B: ClassA {
    // call the constructor from ClassA but without the out-param
}

So I´d know if its good practise or if not how I can avoid declaring the out-param from ClassB.

解决方案

Well, the design of that class is broken anyway, so let's break it a bit more (NOTE! I do not recommend this approach!):

void Main()
{

}

public class ClassA
{
    public ClassA(out bool success)
    {
        success = true;
    }
}

public class B: ClassA
{
    private static bool success;

    // call the constructor from ClassA but without the out-param
    public B()
        : base(out success)
    {
    }
}

Other than that, the closest you can get is making a factory method:

public class B : ClassA
{
    public static B Create()
    {
        bool success;
        var result = new B(out success);
        if (success)
            return result;
        // TODO: Dispose result?
        throw new StupidProgrammerException();
    }
}

这篇关于具有输出参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆