2016-03-02 140 views
9

JavaScript有一個很好的特性,您可以使用一條簡潔的線從對象中的屬性中分配多個變量。它被稱爲destructuring assignment在ES6中添加的語法。解構賦值 - C#中變量的對象屬性

// 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#中執行此操作?

回答

11

它可以幫助你的元組最近的事情。

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

現在它是不可能的。

+3

另請參閱[建議功能](https://github.com/dotnet/roslyn/blob/future/docs/features/patterns.md#user-content-destructuring-assignment) –

+1

查看已更新的[[提出的功能](https://github.com/dotnet/roslyn/blob/features/patterns/docs/features/patterns.md#destructuring-assignment) – styfle

+1

是的,C#7.0支持解構:https://blogs.msdn。 microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/#user-content-deconstruction – paulie4