gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:35 24 4
gpt4 key购买 nike

<分区>

将函数的返回值包装在一个类中是个好主意吗?它简化了编码,您可以避免 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...?
}

}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com