C# 条件使用和默认参数

标签 c#

假设,我们有一个基于某些文件、连接或其他资源的操作。

我们需要一个方法,可以使用提供的资源运行,或者 - 如果没有提供 - 创建自己的:

string Foo(Resource parameter = null)
{
    if (parameter == null)
    {
        using (var res = new Resource)
        {
            res.Something();
               /*......*/
               /*......*/
               /*......*/
            return /*..........*/
        }
    }
    else 
    {
            parameter.Something();
               /*......*/
               /*......*/
               /*......*/
            return /*..........*/
    }
 }

它有效,但这对我来说真的很难看。 这是一种以更紧凑和“漂亮”的方式编写它的方法吗?

我不能使用:

string Foo(Resource parameter = null)
{
    using (var res = parameter ?? new Resource())
    {
        res.Something();
           /*......*/
           /*......*/
           /*......*/
        return /*..........*/
    }
}

因为如果作为参数传递,它会处理我的原始资源。

附言。这个问题的正确标签是什么? #coding-style 被标记为“不使用”。

最佳答案

如果 parameter 为空,一个简单的方法就是递归:

string Foo(Resource parameter = null)
{
    if (parameter == null)
    {
        using (var res = new Resource())
        {
            return Foo(res);   
        }
    }
    else 
    {
        parameter.Something();
        ...
        return ...;
    }
}

你只会递归一次,所以你不需要担心无限堆栈等。

关于C# 条件使用和默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197512/

相关文章:

C# Lambda 表达式 : Why should I use them?

c# - 未捕获重新抛出异常

c# - 将字节数组扫描为 uint 数组

c# - AWS S3 直接上传返回无效签名(版本 4 签名)C#

c# - 从源代码管理发布时如何启用 Windows Azure 的 Code First Entity Framework 迁移?

c# - 方法中的参数检查

C#.net读取Visual Studio 2017 privateregistry.bin文件

c# - 设置 C# 可选参数的默认值

c# - 如何从 XElement 获取字符串形式的 XML 片段?

c# - SQL模拟一个foreach