本文介绍了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表达体构造器
发布评论