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

有C#数组与对象使用困扰:如何实现类似JS的对象数组?

在C#中实现类似JavaScript对象数组的几种方式

C#是强类型语言,和JavaScript的弱类型特性不同,实现类似功能主要有以下几种方式:

1. 自定义实体类(强类型,推荐)

这是C#中最规范的做法,适合需要反复使用该对象结构的场景。先定义对应结构的类,再创建数组或List<T>(List比数组更灵活,支持动态添加元素):

// 定义实体类
public class MyObject
{
    public string Name { get; set; }
    public string Text { get; set; }
    public int Turn { get; set; }
}

// 创建数组
var objectArray = new MyObject[2];
objectArray[0] = new MyObject
{
    Name = "Test",
    Text = "Hello!",
    Turn = 25
};
objectArray[1] = new MyObject
{
    Name = "Test2",
    Text = "Hello, the second time!",
    Turn = 27
};

// 更常用的List方式
var objectList = new List<MyObject>
{
    new MyObject { Name = "Test", Text = "Hello!", Turn = 25 },
    new MyObject { Name = "Test2", Text = "Hello, the second time!", Turn = 27 }
};

2. 使用匿名类型数组

如果只是临时存储一组数据,不想单独定义类,可以用匿名类型。但匿名类型的作用域仅限于当前方法,无法作为方法返回值或类成员:

var objectArray = new[]
{
    new { Name = "Test", Text = "Hello!", Turn = 25 },
    new { Name = "Test2", Text = "Hello, the second time!", Turn = 27 }
};

3. 使用dynamic类型数组

这种方式和JavaScript的写法最接近,通过dynamic跳过编译时类型检查,运行时动态解析属性。但会丢失强类型的安全性,容易引发运行时错误,仅适合快速测试或特殊场景:

var objectArray = new dynamic[2];
objectArray[0] = new { Name = "Test", Text = "Hello!", Turn = 25 };
objectArray[1] = new { Name = "Test2", Text = "Hello, the second time!", Turn = 27 };

// 或者用List<dynamic>
var objectList = new List<dynamic>
{
    new { Name = "Test", Text = "Hello!", Turn = 25 },
    new { Name = "Test2", Text = "Hello, the second time!", Turn = 27 }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:50:40