[英]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>
. 我对C#相当陌生,在将对象转换为
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. 我一直在收到错误消息“无法将类型
Attachment
隐式转换为System.Collections.Generic.List<Attachment>
。我已经查看了很多有关类似错误的文章,但我似乎无法弄清楚我迷路了。
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>
. 该错误发生在我试图将我的Attachment对象转换为
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
. 您正在将
List<T>
设置为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
,并将其设置为string
常量。
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>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.