假设我们有一个基于某些文件,连接或其他资源的操作。
我们需要一种可以与提供的资源一起运行的方法,或者-如果未提供,则创建自己的方法:
string Foo(Resource parameter = null)
{
if (parameter == null)
{
using (var res = new Resource)
{
res.Something();
/*......*/
/*......*/
/*......*/
return /*..........*/
}
}
else
{
parameter.Something();
/*......*/
/*......*/
/*......*/
return /*..........*/
}
}
Run Code Online (Sandbox Code Playgroud)
}
它有效,但这对我来说真的很丑。是否可以用更紧凑,更“漂亮”的方式编写它?
我不能使用:
string Foo(Resource parameter = null)
{
using (var res = parameter ?? new Resource())
{
res.Something();
/*......*/
/*......*/
/*......*/
return /*..........*/
}
}
Run Code Online (Sandbox Code Playgroud)
因为如果作为参数传递它会处理我的原始资源。
PS。这个问题的正确标签是什么?#coding-style标记为“请勿使用”。
c# ×1