如何将类对象强制转换为列表

本文关键字:转换 列表 对象 | 更新日期: 2023-09-27 18:18:56

我是c#的新手,我在将对象转换为List<T>时遇到了麻烦。我一直收到错误"不能隐式转换类型AttachmentSystem.Collections.Generic.List<Attachment>。我看过很多关于类似错误的帖子,但我似乎不知道我错过了什么。

我的核心对象看起来像:

public class Attachment 
{
    public Attachment() { }
    ...
}

它在另一个类的构造函数中被调用,像这样:

public class MyClass
{
    ...
    public List<Attachment> attachments { get; set; };
    ...
    public MyClass(JObject jobj)
    {
        ...
        //Attachments
        if (jobj["attachments"] != null)
        {
            attachments = (Attachment)jobj.Value<Attachment>("attachments");
        }
    }
}

错误发生在我试图将附件对象转换为List<attachments>的最后一行代码中。我明白这句话的意思,但是我所做的一切都没有用。

如何将类对象强制转换为列表

您正在设置List<T>T

attachments = (Attachment)jobj.Value<Attachment>("attachments");
相反,您可能想要添加它。但是不要忘记先实例化列表。
attachments = new List<Attachment>();
attachments.Add((Attachment)jobj.Value<Attachment>("attachments"));

从不涉及泛型的角度来考虑。假设我有一个int x,我把它设置为string常数。

int x = "test";

那是什么意思?它们是完全不同的类型。这有点像你要求编译器执行的转换。左边的类型必须是(或的多态父)右边的类型

直接使用ToObject方法

List<Attachment> attachments = jobj["attachments"].ToObject<List<Attachment>>();
相关文章: