JavaScript有一个很棒的功能,您可以使用一条简洁的线条从对象的属性中分配多个变量。它在ES6中添加了destructuring assignment语法。
// New object
var o = {p1:'foo', p2:'bar', p3: 'baz'};
// Destructure
var {p1, p2} = o;
// Use the variables...
console.log(p1.toUpperCase()); // FOO
console.log(p2.toUpperCase()); // BAR
我想用C#做类似的事情。
// New anonymous object
var o = new {p1="foo", p2="bar", p3="baz"};
// Destructure (wrong syntax as of C#6)
var {p1, p2} = o;
// Use the variables...
Console.WriteLine(p1.ToUpper()); // FOO
Console.WriteLine(p2.ToUpper()); // BAR
在C#中是否有语法?
答案 0 :(得分:20)
最有帮助你的是Tuples。
C#7可能会有这样的东西:
public (int sum, int count) Tally(IEnumerable<int> values)
{
var res = (sum: 0, count: 0); // infer tuple type from names and values
foreach (var value in values) { res.sum += value; res.count++; }
return res;
}
(var sum, var count) = Tally(myValues); // deconstruct result
Console.WriteLine($"Sum: {sum}, count: {count}");
链接到discussion
现在不可能。
答案 1 :(得分:7)
您可以构建和破坏元组。 Snippet
var payLoad = (
Username: "MHamzaRajput",
Password: "password",
Domain: "www.xyz.com",
Age: "24"
);
// Hint: You just need to follow the sequence.
var (Username, Password, Domain, Age) = payLoad;
// or
var (username, password, _, _) = payLoad;
Console.WriteLine($"Username: {username} and Password: {password}");
输出
Username: MHamzaRajput and Password: password
答案 2 :(得分:3)
C#6有很多新的很酷的句法功能,但不幸的是不支持你的问题中描述的解构 - https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6