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

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.
主站蜘蛛池模板: 曲阳县| 栾川县| 淮北市| 永城市| 阿巴嘎旗| 湘西| 桂东县| 巴彦淖尔市| 太和县| 景泰县| 合江县| 长白| 丹棱县| 马公市| 溧阳市| 翼城县| 商水县| 进贤县| 绵阳市| 炉霍县| 合山市| 崇左市| 右玉县| 黑龙江省| 灵宝市| 濮阳县| 交城县| 彰化市| 鄂托克旗| 芷江| 保靖县| 平湖市| 崇明县| 汶川县| 惠东县| 北宁市| 建水县| 无极县| 贵州省| 潢川县| 赞皇县|