c# - 包装函数的返回值是个好主意吗?

标签 c# .net function

<分区>

将函数的返回值包装在一个类中是个好主意吗?它简化了编码,您可以避免 try...catch 我正在考虑做这样的事情。

public class ResultWrapper
{
    public bool Success{get;set;}
    public Exception ErrorMessage{get;set;}
    public object Result{get;set;} //not object essentially(any type) 

    public Result()
    {
            Success=false;
            ErrorMessage="";
            Result=null;
    }
}

public ResultWrapper DoSomething(parameters....)
{
    var result=new ResultWrapper()
    try
    {

    }
    catch(Exception ex)
    {
        result.Error=ex;
    }
    return result;

}

然后像这样调用它

static void main()
{
    var result=DoSomething(parameters...);
    if(result.Success)
    {
        //Carry on with result.Result;
    }
    else
    {
        //Log the exception or whatever... result.Error
    }
}

编辑:

考虑一下

static void main()
{
    var result=Login(); //throws an exception
    if(result.Success)
    {
        //retrive the result
        //carry on
        result=PostSomeStuff(parameter);
        if(result.Success)
        {

        }
        else
        {
            Console.WriteLine("Unable to Post the data.\r\nError: {0}",result.Error.Message);
        }
    }
    else
    {
        Console.WriteLine("Unable to login.\r\nError: {0}",result.Error.Message);
    }
}

在每个函数外包装一个 try..catch 不是更简单吗???

static void main()
{
    try
    {
        var result=Login();
        var result1=result=PostSomeStuff(parameter);
        // a lot of functions doing seprate things.

    }
    catch(Exception ex)
    {
        //what to do...?
    }

}

最佳答案

不,这是一个反模式。如果有任何你不知道如何处理的异常,那就让它向上传播。当语言支持异常时,在返回值中返回异常对象是一个非常糟糕的主意。

如果方法成功应该直接返回值;如果失败,它应该抛出异常。 (注意:某些方法可能返回 bool 表示成功或失败,并将结果存储在 out 参数中。例如, int.TryParse()Dictionary<TKey, TValue>.TryGetValue() 等。由于异常可能代价高昂,因此某些操作可能会更好适合于简单地返回一个指示失败的标志如果预计失败会很频繁,但这应该很少发生。)

关于c# - 包装函数的返回值是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25492855/

相关文章:

c# - 如何读取.Doc模板文件并使用值编辑模板?

c# - 使用 AT 命令的 C# 类?

.net - 如何在 Visual C++ .net 中将一个项目从一个列表框转移到另一个

javascript - QML - 将 JS 函数的代码作为字符串获取

c++ - 该函数应返回 1 但它返回 0

c# - 在 c# 中将整数列表附加到 SQL Server 查询。我怎样才能做到这一点?

c# - 从 Azure Blob 存储读取文件

.net - 如何确定程序终止后是否关闭DOS控制台

c# - PropertyAttributes.HasDefault 和 PropertyBuilder.SetConstant 的含义

C 和 SDL 退出函数