首页 > 编程语言 >Expression-bodied members (C# programming guide)

Expression-bodied members (C# programming guide)

时间:2024-10-18 23:00:14浏览次数:1  
标签:body string C# bodied programming class expression public

Expression body definitions let you provide a member's implementation in a concise, readable form. You can use an expression body definition whenever the logic for any supported member, such as a method or property, consists of a single expression. An expression body definition has the following general syntax:

C#

member => expression;
where expression is a valid expression.

Expression body definitions can be used with the following type members:

Method
Read-only property
Property
Constructor
Finalizer
Indexer
Methods
An expression-bodied method consists of a single expression that returns a value whose type matches the method's return type, or, for methods that return void, that performs some operation. For example, types that override the ToString method typically include a single expression that returns the string representation of the current object.

The following example defines a Person class that overrides the ToString method with an expression body definition. It also defines a DisplayName method that displays a name to the console. The return keyword is not used in the ToString expression body definition.

C#

using System;

namespace ExpressionBodiedMembers;

public class Person
{
   public Person(string firstName, string lastName)
   {
      fname = firstName;
      lname = lastName;
   }

   private string fname;
   private string lname;

   public override string ToString() => $"{fname} {lname}".Trim();
   public void DisplayName() => Console.WriteLine(ToString());
}

class Example
{
   static void Main()
   {
      Person p = new Person("Mandy", "Dejesus");
      Console.WriteLine(p);
      p.DisplayName();
   }
}

For more information, see Methods (C# Programming Guide).

Read-only properties
You can use expression body definition to implement a read-only property. To do that, use the following syntax:

C#

PropertyType PropertyName => expression;
The following example defines a Location class whose read-only Name property is implemented as an expression body definition that returns the value of the private locationName field:

C#

public class Location
{
   private string locationName;

   public Location(string name)
   {
      locationName = name;
   }

   public string Name => locationName;
}

For more information about properties, see Properties (C# Programming Guide).

Properties
You can use expression body definitions to implement property get and set accessors. The following example demonstrates how to do that:

C#

public class Location
{
   private string locationName;

   public Location(string name) => Name = name;

   public string Name
   {
      get => locationName;
      set => locationName = value;
   }
}

For more information about properties, see Properties (C# Programming Guide).

Events
Similarly, event add and remove accessors can be expression-bodied:

C#

public class ChangedEventArgs : EventArgs
{
   public required int NewValue { get; init; }
}

public class ObservableNum(int _value)
{
   public event EventHandler<ChangedEventArgs> ChangedGeneric = default!;

   public event EventHandler Changed
   {
      // Note that, while this is syntactically valid, it won't work as expected because it's creating a new delegate object with each call.
      add => ChangedGeneric += (sender, args) => value(sender, args);
      remove => ChangedGeneric -= (sender, args) => value(sender, args);
   }

   public int Value
   {
      get => _value;
      set => ChangedGeneric?.Invoke(this, new() { NewValue = (_value = value) });
   }
}

For more information about events, see Events (C# Programming Guide).

Constructors
An expression body definition for a constructor typically consists of a single assignment expression or a method call that handles the constructor's arguments or initializes instance state.

The following example defines a Location class whose constructor has a single string parameter named name. The expression body definition assigns the argument to the Name property.

C#

public class Location
{
   private string locationName;

   public Location(string name) => Name = name;

   public string Name
   {
      get => locationName;
      set => locationName = value;
   }
}

For more information, see Constructors (C# Programming Guide).

Finalizers
An expression body definition for a finalizer typically contains cleanup statements, such as statements that release unmanaged resources.

The following example defines a finalizer that uses an expression body definition to indicate that the finalizer has been called.

C#

public class Destroyer
{
   public override string ToString() => GetType().Name;

   ~Destroyer() => Console.WriteLine($"The {ToString()} finalizer is executing.");
}

For more information, see Finalizers (C# Programming Guide).

Indexers
Like with properties, indexer get and set accessors consist of expression body definitions if the get accessor consists of a single expression that returns a value or the set accessor performs a simple assignment.

The following example defines a class named Sports that includes an internal String array that contains the names of some sports. Both the indexer get and set accessors are implemented as expression body definitions.

C#

using System;
using System.Collections.Generic;

namespace SportsExample;

public class Sports
{
   private string[] types = [ "Baseball", "Basketball", "Football",
                              "Hockey", "Soccer", "Tennis",
                              "Volleyball" ];

   public string this[int i]
   {
      get => types[i];
      set => types[i] = value;
   }
}

For more information, see Indexers (C# Programming Guide).

See also
.NET code style rules for expression-bodied-members

标签:body,string,C#,bodied,programming,class,expression,public
From: https://www.cnblogs.com/DesertCactus/p/18475199

相关文章

  • Promise.each()
    原文:http://bluebirdjs.com/docs/api/promise.each.html 正文:Promise.each是一个异步迭代函数,它接受一个可迭代对象(例如数组)或一个可迭代对象的Promise,并在每个元素上执行给定的迭代器函数。如果元素是一个Promise,迭代器会等待它解决后再继续。迭代器函数的签名是(value,i......
  • 算法笔记 C/C++快速入门 | 全章节整理
    目录零.【C语言中的输入和输出函数】sscanf应用场景1:解析用户输入应用场景2:解析文件内容应用场景3:处理网络协议数据应用场景4:字符串解析和数据转换应用场景5:解析复杂的日志数据其他应用场景:scanf 一【编程语言相关】c和cpp二.【数据结构相关】结构体循环定......
  • 深度学习_多层感知机基于Heart Disease UCI 数据集中的processed.cleveland.data训练
    多层感知机(Muti-Layerperceptron)#1.数据导入importpandasaspdnames=["age","sex","cp","trestbps","chol","fbs","restecg",......
  • C语言指针
    1.程序中地址与指针实例讲解Hi!欢迎来到指针的世界,也许您早已听过它的大名,指针被称为是C语言的精华所在。真正理解和掌握指针是征服C语言的关键所在!在众多的计算机语言中,试问:还有哪门语言可以有C语言这样在作用、速度和安全上平衡得如此优异的呢?而指针则在其中扮演了重要的角......
  • Visual Basic 开发环境语言超详细教程详解总结
    一、章节目录VisualBasic语言简介VisualBasic开发环境VisualBasic语法基础控制结构数组与集合过程与函数用户界面设计文件操作数据库访问学习VisualBasic的方法VisualBasic语言教程简介与总结二、各章节知识点总结VisualBasic语言简介VisualBasic(简称V......
  • 牛马阅读(知识+重点翻译) Advanced Deep-Learning Techniques for Salient and Category
    ABSTRACT目标检测,包括目标检测(OD)、显著目标检测(SOD)和特定类别的目标检测(COD),是计算机视觉界最基本但最具挑战性的问题之一。在过去的几十年中,研究人员已经做出了巨大的努力来解决这个问题,因为它在其他计算机视觉任务(如活动或事件识别、基于内容的图像检索和场景理解)中得......
  • POLIR-Society-Organization-Psychology-Training: The Junto Institute: {Relationsh
    POLIR-Society-Organization-Psychology-Emotionhttps://www.thejuntoinstitute.com/Emotionalintelligencetrainingformanagers&leadersintheremoteworkplace.HowYourCompanyBenefitsBettermanagersforimprovedemployeeperformanceHighermanag......
  • 2024/10/18日 日志 --》关于MySQL中的 事务 以及JDBC的初步学习笔记与整理
    今天学习练习了事务的相关内容,并正式向连接数据库走近,进入到JDBC的学习。点击查看代码--事务--概念简介:是一种机制,一个操作序列,包含了一组数据库操作命令。-- 事务把所有的命令作为一个整体一起向系统提交或撤销操作请求,--即这一组数据库命令要么同时成功,要么同时失......
  • ASP.NET Core PDF viewers components Crack
    ASP.NETCorePDFviewerscomponentsCrackASP.NETCorePDFviewerscomponentswithformfillingsupportletusersdirectlycomplete,edit,andsubmitdatawithinPDFforms.TheabilitytoreadandwriteformfieldsinaPDFviewercomponenten......
  • Easily Conceal Sensitive Information in Your Images
    EasilyConcealSensitiveInformationinYourImagesSyncfusionEssentialStudioASP.NETMVC2024Volume3enablesdeveloperstoredactimagesbyblurringorpixelatingsensitivesections.SyncfusionEssentialStudioASP.NETMVC,availableaspa......