C#7表达体构造器

编程入门 行业动态 更新时间:2024-10-22 14:40:40
本文介绍了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表达体构造器

本文发布于:2023-11-03 15:42:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555475.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!