C#7表达体构造器 [英] C# 7 Expression Bodied Constructors

查看:86
本文介绍了C#7表达体构造器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#7中,如何使用2个参数编写这样的表达式体构造器。

In C# 7, how do I write an Expression Bodied Constructor like this using 2 parameters.

public Person(string name, int age)
{
  Name = name;
  Age = age;
}


推荐答案

一种方法是使用元组和解构以允许在一个表达式中进行多个分配:

A way to do this is to use a tuple and a deconstruction to allow multiple assignments in one expression:

public class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age) => (Name, Age) = (name, age);
}

从C#7.1开始(Visual Studio 2017 Update 3引入),编译器代码现在将优化元组的实际构造和解构。因此,与长期分配相比,这种方法没有性能开销。

As of C# 7.1 (introduced with Visual Studio 2017 Update 3), the compiler code will now optimise away the actual construction and deconstruction of the tuple. So this approach has no performance overhead when compared with "longhand" assignment.

这篇关于C#7表达体构造器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆