当前位置:  开发笔记 > 编程语言 > 正文

最佳实践:函数返回值或byref输出参数?

如何解决《最佳实践:函数返回值或byref输出参数?》经验,为你挑选了1个好方法。

我有一个名为FindSpecificRowValue的函数,它接受一个数据表并返回包含特定值的行号.如果找不到该值,我想向调用函数指示.

是最好的方法:

    编写一个函数,如果找不到则返回false,如果找到则返回true,找到的行号作为byref/output参数,或者

    编写一个返回int的函数,如果找不到行值则返回-999,如果是行号则返回行号?

angry person.. 13

就个人而言,我不会使用该方法名称.

我会改为两种方法:

TryFindSpecificRow
FindSpecificRow

这将遵循Int32.Parse/TryParse的模式,在C#中它们可能如下所示:

public static Boolean TryFindSpecificRow(DataTable table, out Int32 rowNumber)
{
    if (row-can-be-found)
    {
        rowNumber = index-of-row-that-was-found;
        return true;
    }
    else
    {
        rowNumber = 0; // this value will not be used anyway
        return false;
    }
}

public static Int32 FindSpecificRow(DataTable table)
{
    Int32 rowNumber;


    if (TryFindSpecificRow(table, out rowNumber))
        return rowNumber;
    else
        throw new RowNotFoundException(String.Format("Row {0} was not found", rowNumber));
}

编辑:更改为更适合问题.



1> angry person..:

就个人而言,我不会使用该方法名称.

我会改为两种方法:

TryFindSpecificRow
FindSpecificRow

这将遵循Int32.Parse/TryParse的模式,在C#中它们可能如下所示:

public static Boolean TryFindSpecificRow(DataTable table, out Int32 rowNumber)
{
    if (row-can-be-found)
    {
        rowNumber = index-of-row-that-was-found;
        return true;
    }
    else
    {
        rowNumber = 0; // this value will not be used anyway
        return false;
    }
}

public static Int32 FindSpecificRow(DataTable table)
{
    Int32 rowNumber;


    if (TryFindSpecificRow(table, out rowNumber))
        return rowNumber;
    else
        throw new RowNotFoundException(String.Format("Row {0} was not found", rowNumber));
}

编辑:更改为更适合问题.

推荐阅读
Chloemw
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有