c# - 将 expression-bodied 与 throw 混合用于多个参数

标签 c# c#-7.0

这可能是一件容易的事。但如果可能的话,我无法解决这个问题。

因为我们可以将表达式体成员应用于构造函数,并且因为表达式体成员可以使用 throw 表达式,所以我们可以简化以下代码

public class Foo
{
    public string ProA { get; set; }
    public Foo(string proa)
    {
        if (proa == null)
        {
            throw new ArgumentNullException("Invalid proa value");
        }
        ProA = proa;
    }
}

上面的代码可以简化为:

public class Foo
{
    public string ProA { get; set; }
    public Foo(string proa) => ProA = proa ?? 
        throw new ArgumentNullException("Invalid proa value");
}

问题:在我的例子中,我有多个参数(在参数化构造函数中)在构造时解析,如果有人可以帮助我简化以下代码,那将非常有帮助构造函数的表达式体成员以及在 null 情况下抛出的表达式

public class Bar
{
    public string ProA { get; set; }
    public string ProB { get; set; }
    public Bar(string proa, string prob)
    {
        if (proa == null)
            throw new ArgumentNullException("Invalid proa value");
        else if (prob == null)
            throw new ArgumentNullException("Invalid prob value");

        ProA = proa;
        ProB = prob;
    }
}

最佳答案

Question: In my case, I have more than one parameter (in a parameterised constructor ) to parse while construction and would be very helpful if someone can help me to simplify following code with the help of expression-bodied members to constructors along with throwing expressions in case of null

表达式体成员在 C# 7.0 中得到扩展,现在包括将它们与构造函数一起使用。该方法由一个单个表达式组成,该表达式返回一个类型与该方法的返回类型相匹配的值,或者对于返回 void 的方法,该表达式执行某些操作

让我们看一下您的第一个简化代码块...

public class Foo
{
    public string ProA { get; set; }
    public Foo(string proa) => ProA = proa ?? 
        throw new ArgumentNullException("Invalid proa value");
}

这里使用表达式主体就可以了,并且只包含一个表达式,所以它是有效的。

public Foo(string proa) => ProA = proa ?? 
            throw new ArgumentNullException("Invalid proa value");

当您有多个参数时,就会出现问题,需要处理多个参数,而不是有主体声明,表达式主体应该派上用场并起作用,它们确实起作用了。

这是一种实现此目的的方法,同时使其有效。

public Bar(string proa, string prob) => 
            (ProA, ProB) = (proa ?? throw new ArgumentNullException("Invalid proa value"),
            prob ?? throw new ArgumentNullException("Invalid prob value"));

基本上我在这里做的是创建一个 ValueTuple Struct以及deconstructing这让您只需一次操作即可解包元组中的所有项目。

可以做的另一个选择,但更多的工作是调用类中的例程以在构造时设置类。事实证明,走这条路比处理常规 body 的变化要麻烦。

引用资料:

Expression-bodied Members

关于c# - 将 expression-bodied 与 throw 混合用于多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58842321/

相关文章:

javascript - c# 限制在gridview中选择的复选框数量

c# - 将存档文件中的 Stream 转换为 Byte[]

c# - 客户端支持 C# 7.0 所需的最低版本的 .NET

c# - 为什么此方法组转换在 C# 7.2 及更低版本中不明确?

c# - 十进制值检查是否为零

c# - 如何以编程方式将 xml 转换为 excel 文件

c# - 为多个客户自定义 c# WinForm 应用程序

c# - 枚举 COM/DCOM/COM+ IN_PROC 实例

c# - VS2017错误调试元组任务

c# - 模式匹配案例 when