如何用void方法实现早期返回(或覆盖返回)而不是bool()

时间:2015-12-12 14:28:36

标签: c# design-patterns override new-operator

我试图做类似下面代码的操作,以避免使用Boolean返回类型方法,我找不到任何正确实现它的方法:

public void myMethod(int someInitializingParameter)
{
                                              //return (kinda override operator)
     if(TargetObjToinitItsProperties == null) MsgDbgWinShow("Error: Line#637-xxx.CS", "Property was accessed prior to parent object init");
     TargetObjToInitItsProperties.IntProp1 = someInitializingParameter;
}

static void MsgDbgWinShow(string Wtitle, string Wmsg)
{
   create a window (windowsTitle=Wtitle .. size width ...create TextBlock.Content= Wmsg...etc')

   CreatedWindow.Show();
//here is self exit and return ...from self but will not act as return operator...
}

有没有办法将void用作返回类型,而不是使用Type?

1 个答案:

答案 0 :(得分:1)

您可以简单地抛出异常并在调用者中捕获它。 这使得方法处于你抛出'throw'的位置:

    public void myMethod(int someInitializingParameter)
    {
        //return (kinda override operator)
        if(TargetObjToinitItsProperties == null)
            throw new Exception("Property was accessed prior to parent object init");

        TargetObjToInitItsProperties.IntProp1 = someInitializingParameter;
    }

当您从中继承异常时,甚至可以创建自己的异常类型。然后你可以输入一些额外的数据:

class MyException : Exception
{
    // some enhancements
    public string ExtraData;

    public MyException(string sMessage, string sExtraData)
        : base(sMessage)
    {
        ExtraData = sExtraData;
    }
}

现在你可以扔掉它:

    public void myMethod(int someInitializingParameter)
    {
        //return (kinda override operator)
        string sExtraData = "Hallo";
        if (TargetObjToinitItsProperties == null)
            throw new MyException("Property was accessed prior to parent object init",
                                  sExtraData);

        TargetObjToInitItsProperties.IntProp1 = someInitializingParameter;
    }

在调用者中,您可以捕获它并使用额外的数据:

    public void CallingMethod()
    {
        try
        {
            myMethod(23);
        }
        catch (MyException e)
        {
            Console.WriteLine(e.Message + e.ExtraData);
        }
    }