官术网_书友最值得收藏!

How to do it...

  1. 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; }
}
  1. 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;
}
  1. 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;
}
}
  1. 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}");
  1. Running the Console Application will display the deconstructed values returned from the Student class.
  1. 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; }
}
  1. 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;
}
  1. 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.
主站蜘蛛池模板: 吉安县| 资溪县| 兴安盟| 湟中县| 阿鲁科尔沁旗| 广州市| 巩留县| 齐齐哈尔市| 来宾市| 安宁市| 洛浦县| 伊吾县| 屏南县| 龙江县| 陈巴尔虎旗| 湖北省| 微博| 嘉鱼县| 柘荣县| 专栏| 北海市| 兴隆县| 招远市| 健康| 雅江县| 镇巴县| 抚州市| 丹东市| 彭山县| 娱乐| 肇东市| 钟祥市| 姚安县| 彝良县| 葵青区| 德惠市| 大同县| 依安县| 宿迁市| 新绛县| 台安县|