c# - C# 中 C++ 结构化绑定(bind)的模拟

在 C++17 中,有一个非常漂亮的功能,称为结构化绑定(bind)。我很难找到它的 C# 模拟。具体来说,我的代码类似于:

public struct A
{
public int up;
public int down;
public int left;
public int right;
};
public abstract A foo();
A a = foo();
int up=a.up;
int down=a.down;
int left=a.left;
int right=a.right;

我想以一种不太冗长的方式初始化这些变量。

提前谢谢你。

最佳答案

你可以这样做:

using System;

public struct A
{
    public int up;
    public int down;
    public int left;
    public int right;
    
    public void Deconstruct(out int up, out int down, out int left, out int right)
    {
        up = this.up;
        down = this.down;
        left = this.left;
        right = this.right;
    }
};

public static class M {
    public static void main() {
        var (up,down,left,right) = new A();
    }
}

或在 C# 10 中:

using System;

record struct A(int up, int down, int left, int right);

public static class M {
    public static void main() {
        var (up,down,left,right) = new A();
    }
}

https://stackoverflow.com/questions/57066817/

相关文章:

jenkins - BlueOcean编辑器 "scm"输入什么

reactjs - Babel 不从当前目录上方的文件转译 JSX

flutter - 如何修复 flutter 上的 "A RenderFlex overflowed

c++ - 如何使用跳过部分 device_vector 的自定义仿函数实现 thrust::tra

angular - Mat-select 滚动不跳转到选定的 mat-option

reactjs - 在 nextjs 中,对象类型从服务器端更改为客户端

amazon-web-services - 如何在数据加载前截断 AWS Glue 作业中的 RDS

reactjs - 如何使用 Jest 和 Enzyme 在 nextjs 应用程序中编写单元测试

spring-boot - spring boot 微服务 docker 实现中 google oa

android - react native : compileDebugJavaWithJavac