【问题标题】:Destructuring assignment - object properties to variables in C#解构赋值 - C# 中变量的对象属性
【发布时间】:2016-06-15 16:58:30
【问题描述】:

JavaScript 有一个非常棒的特性,你可以使用简洁的一行从一个对象的属性中分配多个变量。它被称为destructuring assignment 语法,是在 ES6 中添加的。

// 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# 中有这样的语法吗?

【问题讨论】:

  • 什么场景需要这个功能,很好奇!
  • @TechnicalSmile 不需要此语言功能(或任何语言功能)。这都是零和一之上的语法糖 :) 在这种情况下,我想编写更少的代码,这是一个启用它的功能。

标签: c# syntactic-sugar


【解决方案1】:

最能帮助你的是元组。

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

目前不可能。

【讨论】:

【解决方案2】:

C# 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

【讨论】:

  • 我收到error CS0128: A local variable named _ is already defined in this scope。下划线需要两个不同的名称吗?
  • 我上传了一个sn-p链接,你可以在那里测试。
猜你喜欢
  • 2018-06-16
  • 2016-04-17
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 2011-10-27
  • 2014-12-01
相关资源
最近更新 更多