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

C#中如何将Item对象映射到二维数组?解决无法隐式转换类型的错误

解决Cannot implicitly convert type 'Item' to 'System.Array'的问题

咱们先拆解下你代码里导致错误的几个关键点,然后一步步修正:

1. 构造函数赋值顺序搞反了

你当前的Item构造函数里,赋值方向完全反了——id = this.id;这种写法是把类的成员变量值赋给参数,而不是把参数值存到成员变量里。正确的写法应该是用this关键字明确指向类的成员,把传入的参数赋值给它们:

public Item(int id, int price, int stock) { 
    this.id = id; 
    this.price = price; 
    this.stock = stock; 
}

2. 二维数组的类型声明错误

你现在声明的是new Array[50,50],这是一个用来存储System.Array对象的数组,而你要存的是自定义的Item对象,类型完全不匹配,这就是报错的核心原因。

你需要声明一个**Item类型的二维数组**,语法是Item[,]:

var myArray = new Item[50,50]; 

3. 变量名大小写不一致(C#大小写敏感)

代码里你先定义了myArray,后面又写了myarray[0,2]——C#是区分大小写的,这会被当成两个不同的变量,直接编译报错,要统一成同一个名称:

myArray[0,2] = second; 

修正后的完整代码

public class Item { 
    public int id; 
    public int price, stock; 
    public Item(int id, int price, int stock) { 
        this.id = id; 
        this.price = price; 
        this.stock = stock; 
    } 
} 

static void Main(string[] args) { 
    Item first = new Item(1, 23, 2); 
    Item second = new Item(2, 345, 5); 
    var myArray = new Item[50,50]; 
    myArray[0,1] = first; 
    myArray[0,2] = second; 
}

这样修改后,代码就能正常编译,Item对象也能正确存入二维数组啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:53:11