简体   繁体   中英

How can I cast a class object to a list?

I'm fairly new to C# and I'm having trouble converting an object to a List<T> . I've been receiving the error "Cannot implicitly convert type Attachment to System.Collections.Generic.List<Attachment> . There are lots of posts about similar errors that I've looked over, but I can't seem to figure out what I'm missing.

My core object looks like:

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

It's being called in another class' constructor like so:

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

The error is occurring in the last line of code where I'm trying to cast my Attachment object to the List<attachments> . I understand what the message is saying, but everything I've tried doesn't work.

You are setting a List<T> to a T .

attachments = (Attachment)jobj.Value<Attachment>("attachments");

Instead, you probably want to Add it. But don't forget to instantiate the list first.

attachments = new List<Attachment>();
attachments.Add((Attachment)jobj.Value<Attachment>("attachments"));

Think about it in terms that don't involve generics. Say I have an int x and I set it to a string constant.

int x = "test";

What would that mean? Those are complete different types. That's kind of like the conversion you're asking the compiler to perform. The type on the left has to be (a polymorphic parent of or) the type on the right.

只需使用ToObject方法

List<Attachment> attachments = jobj["attachments"].ToObject<List<Attachment>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM