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

选择产品值时ProductType[]数组始终返回索引-1,代码求助

问题:选择产品值数组时始终获取到索引-1,求排查代码问题

当我选择产品值数组时,总是获取到ProductType[]数组的索引值-1。请问我的代码是否存在问题?恳请各位提供帮助,谢谢!

ViewModel代码:

public ProductType[] ProductTypesSel { get; set; }
private int _ProductTypeIndex = -1;

public int ProductTypeIndex
{
    get { return _ProductTypeIndex; }
    set
    {
        _ProductTypeIndex = value;

        if (value >= 0)
        {
            Item.ProductType = ProductTypesSel[value].Code;
        }
        
        OnPropertyChanged(nameof(ProductTypeDisp));
        Console.WriteLine(ProductTypeDisp);
    }
}
public string ProductTypeDisp => Config != null && ProductTypeIndex >= 0 && ProductTypeIndex < ProductTypesSel.Length ? ProductTypesSel[ProductTypeIndex].Name : null;  

Codebehind代码:

int indexValue = Array.IndexOf(_Model.ProductTypesSel, productValue);
_Model.ProductTypeIndex = indexValue;

问题分析与解决思路

Array.IndexOf返回-1的核心原因是传入的productValue不在ProductTypesSel数组中,或者对象匹配逻辑不符合预期,具体排查点如下:

  1. 数组初始化检查
    先确认ProductTypesSel数组是否已经正确填充了数据,如果数组为空或未初始化,Array.IndexOf必然返回-1。

  2. 对象匹配逻辑问题
    如果ProductType是自定义引用类型,Array.IndexOf默认会比较对象引用,而不是对象的属性值。也就是说,即使productValue的Code、Name等属性和数组里的某个元素完全一致,但只要它是新创建的实例(不是数组中元素的引用),Array.IndexOf就会返回-1。

  3. 类型一致性检查
    确认productValue的类型确实是ProductType,和数组元素类型完全匹配,避免因类型不匹配导致查找失败。


解决方法

针对对象匹配问题,推荐以下两种方案:

方案1:重写ProductType的Equals和GetHashCode方法

让对象比较基于关键属性(比如Code),示例代码:

public class ProductType
{
    public string Code { get; set; }
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        return obj is ProductType type && Code == type.Code;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Code);
    }
}

重写后,Array.IndexOf会根据Code属性值来匹配对象。

方案2:改用LINQ的Array.FindIndex方法直接按属性查找

不需要修改ProductType类,直接通过指定匹配条件查找索引:

// 假设匹配条件是Code属性相等
int indexValue = Array.FindIndex(_Model.ProductTypesSel, pt => pt?.Code == productValue?.Code);
_Model.ProductTypeIndex = indexValue;

这种方式更灵活,可以根据实际需要调整匹配逻辑(比如用Id、Name等)。

另外,建议在ViewModel的ProductTypeIndex setter中增加ProductTypesSel不为null的判断,避免空引用异常:

if (value >= 0 && ProductTypesSel != null && value < ProductTypesSel.Length)
{
    Item.ProductType = ProductTypesSel[value].Code;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:31:05