解构赋值 - C# 中变量的对象属性

本文关键字:变量 对象 属性 赋值 | 更新日期: 2023-09-27 18:37:01

JavaScript 有一个漂亮的功能,您可以使用一行简洁的行从对象中的属性中分配多个变量。它被称为解构赋值语法,它是在 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# 中是否有执行此操作的语法?

解构赋值 - C# 中变量的对象属性

最接近可以帮助你的东西是元组。

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}"); 

链接到讨论

现在这是不可能的。

C# 7 使用元组。你可以实现这样的事情。

您可以构造和销毁元组。 片段

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

records的位置语法默认带有解构(dotnet fiddle):

public record Person(string firstName, string lastName) {}
var person = new Person("Kyle", "Mit");
var (firstName, lastName) = person;
Console.WriteLine(firstName); // "Kyle"

通过 SharpLab 查看生成的代码,它只是实现了一个常规的Deconstruct方法,如果您不使用记录,您可以将其添加到您自己的类型中:

[CompilerGenerated]
public void Deconstruct(out string firstName, out string lastName)
{
    firstName = this.firstName;
    lastName = this.lastName;
}

根据关于解构的文件

C# 不提供对解构除 recordDictionaryEntry 类型以外的非元组类型的内置支持。但是,作为类、结构或接口的作者,您可以通过实现一个或多个Deconstruct方法允许解构该类型的实例。

我一直在寻找这样的东西一段时间了,我遇到了带有类的解构器。这并不像Javascript给我们的那样优雅,但如果做得好,它绝对可以简化很多事情。

下面是一个小示例(我没有运行此代码)。我希望这对其他人有所帮助:

class Animal
{
    public string name;
    public string type;
    public Animal(
            string name, 
            string type
        )
    {
        this.name = name;
        this.type = type;
    }
    // Use out params with a 
    // method called Deconstruct
    public void Deconstruct(
            out string name, 
            out string type
        )
    {
        name = this.name;
        type = this.type;
    }
}
class Shelter
{
    public Animal[] animals;
    public int animalCapacity;
    public int numberOfAnimalsInShelter = 0;
    public Shelter(
            int animalCapacity
        )
    {
        this.animalCapacity = animalCapacity;
        animals = new Animal[animalCapacity];
    }
    public void AddAnimalToShelter(
            Animal animal
        )
    {
        animals[numberOfAnimalsInShelter] = animal;
        numberOfAnimalsInShelter++;
    }
    public void AnimalsInShelter()
    {
        for (int i = 0; i < animals.Length; i++)
            {
            // Here is how to use the Deconstructor 
            // method from the Animal class
                var (name, type) = animals[i];
                Console.WriteLine(name);
                Console.WriteLine(type);
            }
    }
}

输出应该是添加到收容所的每只动物的名称和类型。