You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中继承NamedTuple的Mode类如何等效转换为C#实现

Python NamedTuple 转 C# 实现方案

原Python代码核心是定义了不可变、值比较语义的Mode类型,包含多个可空整数字段与预设默认值,对应C#可按以下方案实现:


最优方案(C# 10+)

使用record struct完全匹配Python NamedTuple的所有特性:

public record struct Mode
{
    public int? inh { get; init; } = null;
    public int inh_sz { get; init; } = 0;
    public int? imm { get; init; } = null;
    public int imm_sz { get; init; } = 0;
    public int? dir { get; init; } = null;
    public int dir_sz { get; init; } = 0;
    public int? ind { get; init; } = null;
    public int ind_sz { get; init; } = 0;
    public int? ext { get; init; } = null;
    public int ext_sz { get; init; } = 0;
    public int? rel { get; init; } = null;
    public int rel_sz { get; init; } = 0;
}

特性匹配说明:

  • 不可变性:init访问器仅允许初始化阶段赋值,和NamedTuple创建后不可修改的特性一致
  • 类型对应:Python中可赋值为None的int字段对应C#的可空值类型int?
  • 相等性:record struct自动生成值相等比较逻辑,和Python NamedTuple的比较行为完全一致
  • 便捷操作:支持with表达式实现非破坏性修改,对应Python NamedTuple的_replace方法

兼容低版本C#的方案(C# 7+)

如果使用的C#版本不支持record struct,可以用自定义结构体实现:

public struct Mode
{
    public int? inh { get; }
    public int inh_sz { get; }
    public int? imm { get; }
    public int imm_sz { get; }
    public int? dir { get; }
    public int dir_sz { get; }
    public int? ind { get; }
    public int ind_sz { get; }
    public int? ext { get; }
    public int ext_sz { get; }
    public int? rel { get; }
    public int rel_sz { get; }

    public Mode(int? inh = null, int inh_sz = 0, int? imm = null, int imm_sz = 0, 
                int? dir = null, int dir_sz = 0, int? ind = null, int ind_sz = 0, 
                int? ext = null, int ext_sz = 0, int? rel = null, int rel_sz = 0)
    {
        this.inh = inh;
        this.inh_sz = inh_sz;
        this.imm = imm;
        this.imm_sz = imm_sz;
        this.dir = dir;
        this.dir_sz = dir_sz;
        this.ind = ind;
        this.ind_sz = ind_sz;
        this.ext = ext;
        this.ext_sz = ext_sz;
        this.rel = rel;
        this.rel_sz = rel_sz;
    }
}

通过get-only属性保证不可变性,构造函数带默认参数,完全匹配原类型的创建语法。


用法对应示例

Python创建实例写法:

my_mode = Mode(inh=0x10, imm_sz=4, rel=0x20)

C#对应写法:

// record struct 简写
var myMode = new Mode { inh = 0x10, imm_sz = 4, rel = 0x20 };
// 低版本构造函数写法
var myMode = new Mode(inh: 0x10, imm_sz: 4, rel: 0x20);

内容的提问来源于stack exchange,提问作者Icemanind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:24:03