- C# 7 and .NET Core Cookbook
- Dirk Strauss
- 419字
- 2021-07-03 00:11:53
How to do it...
- If you created the Student class earlier, you should have something similar to this in your code:
public class Student
{
public string Name { get; set; }
public string LastName { get; set; }
public List<int> CourseCodes { get; set; }
}
- To create a deconstructor, add a Deconstruct method to your Student class. You will notice that this is a void method that takes two out parameters (in this instance). We then just assign the values of Name and LastName to the out parameters.
If we wanted to deconstruct more values in the Student class, we would pass in more out parameters, one for each value we wanted to deconstruct.
public void Deconstruct(out string name, out string lastName)
{
name = Name;
lastName = LastName;
}
- Your modified Student class should now look as follows:
public class Student
{
public string Name { get; set; }
public string LastName { get; set; }
public List<int> CourseCodes { get; set; }
public void Deconstruct(out string name, out string lastName)
{
name = Name;
lastName = LastName;
}
}
- Consuming our Student class (just like we did with Tuples) can now be accomplished as follows:
Student student = new Student();
student.Name = "Dirk";
student.LastName = "Strauss";
var (FirstName, Surname) = student;
WriteLine($"The student name is {FirstName} {Surname}");
- Running the Console Application will display the deconstructed values returned from the Student class.

- Deconstructors can just as easily be used in extension methods. This is quite a nice way to extend the existing type to include a deconstruction declaration. To implement this, we need to remove the deconstructor from our Student class. You can just comment it out for now, but essentially this is what we are after:
public class Student
{
public string Name { get; set; }
public string LastName { get; set; }
public List<int> CourseCodes { get; set; }
}
- The Student class now does not contain a deconstructor. Head on over to the extension methods class and add the following extension method:
public static void Deconstruct(this Student student,
out string firstItem, out string secondItem)
{
firstItem = student.Name;
secondItem = student.LastName;
}
- The extension method acts on a Student type only. It follows the same basic implementation of the deconstructor created earlier in the Student class itself. Running the console application again, you will see the same result as before. The only difference is that the code is now using the extension method to deconstruct values in the Student class.

推薦閱讀
- JavaScript前端開發模塊化教程
- FreeSWITCH 1.8
- vSphere High Performance Cookbook
- Visual C++實例精通
- SQL for Data Analytics
- Cassandra Design Patterns(Second Edition)
- Java Web應用開發技術與案例教程(第2版)
- Building Mapping Applications with QGIS
- JSP開發案例教程
- Nginx Lua開發實戰
- 從零開始學Linux編程
- Android群英傳
- 精通MySQL 8(視頻教學版)
- MySQL 8從零開始學(視頻教學版)
- RESTful Web API Design with Node.js