如何覆盖具有out参数的虚方法?

时间:2015-06-12 23:40:56

标签: c# function virtual-method out-parameters

我的基类中有这个虚方法:

public virtual bool AgregarEtapa(DateTime pFechaIngreso, EtapaEnvio.Etapas pEtapa, OficinaPostal pUbicacion, string pNombreRecibio, out string pMensajeError) 
{
    string mensajeError = "";
    bool sePuedeAgregar = false;

    // more code

    pMensajeError = mensajeError;
    return sePuedeAgregar;
}

以及在子类中覆盖它的方法,如下所示:

public override bool AgregarEtapa(DateTime pFechaIngreso, EtapaEnvio.Etapas pEtapa, OficinaPostal pUbicacion, string pNombreRecibio, out string pMensajeError)
{
    bool seHace = true;
    bool exito = false;

    // more code here

    if (seHace) 
    { 
        base.AgregarEtapa(pFechaIngreso, pEtapa, pUbicacion, pNombreRecibio, out pMensajeError);
        exito = true;
        pMensajeError = ??;
    }

    return exito;
}

我从来没有在重写方法中使用参数,所以我不确定如何声明子方法的out参数。我想两个out参数(child和base)应该以相同的方式调用,但我也不确定。

基本上,我需要在子方法中设置pMensajeError,其值与base方法的out参数返回的值相同。 这应该怎么做?

2 个答案:

答案 0 :(得分:1)

删除JMS

在调用base方法时分配它。

但是,所有代码路径必须导致它被分配,当pMensajeError = ??;为false时,也必须分配它。可以在else语句中分配吗?

答案 1 :(得分:1)

不,您不需要设置pMensajeError = ??;,至少不需要设置pMensajeError。调用base.AgregarEtapa已设置base.AgregarEtapa。如果你真的想给它一个不同的值,你可以重新分配,但是如果你想使用基类实现设置的值,你就不需要做任何特殊的事情。

您唯一需要记住的是,您对if的调用显示在if块内。当base.AgregarEtapa条件为假时,您需要考虑要执行的操作,并且if (seHace) { base.AgregarEtapa(pFechaIngreso, pEtapa, pUbicacion, pNombreRecibio, out pMensajeError); exito = true; } else { pMensajeError = ??; } return exito; 永远不会被调用。

这看起来像这样:

<?php
    $comments_query = new WP_Comment_Query();
    $comments = $comments_query->query( array( 'number' => 5 ) );
    if ($comments)
    {
        foreach ( $comments as $comment ) {
            ?>
            <div class="comment" id="comment-<?php $comment->comment_ID ?>">
                <div class="avatar">
                    <?php get_avatar( $comment->comment_author_email, 48 ); ?>
                </div>
                <div class="text>
                    <a class="author" href="<?php get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment->comment_ID; ?>">
                    <?php get_comment_author( $comment->comment_ID ) ?>
                    </a>
                    <?php strip_tags( substr( apply_filters( 'get_comment_text', $comment->comment_content ), 0, 80 ) ) . '...'; ?></p>
                </div>
            </div>
            <?php
        }
    } else {
        echo 'none.';
    }
?>
相关问题