Deconstructing tuples
c#7.0 has added a number of features, one of which is the new tuple (ValueTuple), which allows us to return multiple values and work with deconstruction more easily, as in the following example
Static void Main(string[] args)
{
(var name, var age) = GetUser();
Console.WriteLine($"name:{name}\nage:{age}");
}
Public static (string name, int age) GetUser()
{
Return ("Zhang San", 11);
}
You can see that the deconstructed tuple can write elegant code, and you can use type inference, but refactoring tuples here is not the point, so pay more attention, and here's an interesting feature
Deconstructing objects
The ability to deconstruct is not only a tuple, but also a more interesting function, which is to deconstruct the object. Does that sound interesting?
Static void Main(string[] args)
{
Var user = new User
{
Name = "Zhang San",
Age = 11,
Email = "zhangsan@126.com",
Sex="male"
};
(var name, var email) = user;
Console.WriteLine($"name:{name}\nemail:{email}");
}
The above code is not very surprised, anyway I first saw when I was particularly surprised, but also feel particularly interesting, then this is how to achieve, in fact, just add a destructor in the class (deconstruct) can, The destructor parameter method name must be deconstruct, the return value must be void, and the argument list must be out
Public class User
{
Public string Name { get; set; }
Public string Email { get; set; }
Public int Age { get; set; }
Public string Sex { get; set; }
//Destructor
Public void Deconstruct(out string name, out string email)
{
Name = Name;
Email = Email;
}
}
is not feeling particularly simple, haha,
Destructors also support overloading
Class Program
{
Static void Main(string[] args)
{
Var user = new User
{
Name = "Zhang San",
Age = 11,
Email = "zhangsan@126.com",
Sex="male"
};
(var name1, var email1) = user;
Console.WriteLine($"name:{name1}\temail:{email1}");
(var name2,var age2, var email2) = user;
Console.WriteLine($"name:{name2}\tage:{age2}\temail:{email2}");
}
}
Public class User
{
Public string Name { get; set; }
Public string Email { get; set; }
Public int Age { get; set; }
Public string Sex { get; set; }
//Destructor
Public void Deconstruct(out string name, out string email)
{
Name = Name;
Email = Email;
}
/ / Structure function overload
Public void Deconstruct(out string name,out int age,out string email)
{
Name = Name;
Age = Age;
Email = Email;
}
}
However, refactoring does not support overloading of parameter consistency
Even if the parameter types are inconsistent
It feels like a parameter type inference error, however,
So destructors are not overloaded with the same number of parameters, even if the parameter types are inconsistent