无法将int[]隐式转换为int?[]

5

在我的示例类中,它包含了一个int?[]类型的IdValues。这些值来自于另一个类,该类具有Id作为关键字段。

//Database class
public class SampleValues // this is a entity that i want to collect the deatil id
{
    public int Id { get; set; }
    public int?[] SampleDetailIdValue { get; set; }
}

public class SampleDetailValues // this is the detail entity
{
    public int Id { get; set; }
}


// The error code
if (sampleDetails.Count > 0)
{
    sample.IdValues = sampleDetails.Select(s => s.Id).ToArray(); // << The error occurred this line.
}

错误信息是无法将类型int[]隐式转换为int?[]
2个回答

6

投射您的内容:

sample.IdValues = sampleDetails.Select(s => (int?)s.Id).ToArray(); 

您正在投影一个 int,调用 ToArray 会给您一个 int[],因此只需投影一个 int?

另外还有 Cast 扩展方法:

sample.IdValues = sampleDetails
    .Select(s => s.Id) 
    .Cast<int?>()
    .ToArray(); 

1
无法进行隐式转换,但可以尝试进行显式转换。
sample.IdValues = sampleDetails.Select(x => x.Id)
                               .Cast<int?>()
                               .ToArray();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接