通用列表和 CollectionDataContract 之间的转换问题
我定义了以下集合契约:
[CollectionDataContract(Name = "Centres")]
public class Centres : List<Centre>
{}
并定义了以下操作契约来返回此集合
public Model.Centres GetCentres()
{
List<Centre> allCentres = (from c in Model.Centre.GetCentres()
where c.Visible == true
select c).ToList();
return allCentres
}
但是当我运行代码时,我收到了 ExplicitCastException。据我所知,我正在尝试将中心列表(列表)放入我的集合“中心”中,该集合本身源自列表。这是否可能,或者通过派生一个新对象,我是否创建了一种无法以这种方式工作的新型列表。
我当前解决此问题的方法是声明一个新的 Centers 实例,并使用 foreach 将所有中心复制到其中。
I have the following collection contract defined:
[CollectionDataContract(Name = "Centres")]
public class Centres : List<Centre>
{}
and the following operation contract defined to return this collection
public Model.Centres GetCentres()
{
List<Centre> allCentres = (from c in Model.Centre.GetCentres()
where c.Visible == true
select c).ToList();
return allCentres
}
But when I run the code I receive an ExplicitCastException. So as far as I can see I'm trying to cast a list of centres (List) into my collection 'Centres' which itself derives from List. Is this possible or by deriving a new object am I creating a new type of list that won't work in this way.
My current work around for this problem is to declare a new instance of Centres and copy all centres into it using a foreach.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是
Centres
“是”List
,List
不是Centres
。尽管
Centres
没有实现,它仍然是List
的子类,您可以扩展您的Centres
类以进行隐式转换运算符,或者,也许向 Centers 添加一个以List
作为参数的构造函数。尝试将
Centres
更改为诸如...之类的内容,然后它将允许从
List进行隐式转换。
The problem is
Centres
"is a"List<Centre>
,List<Centre>
is not aCentres
.Despite
Centres
having no implementation it is still a sub-class ofList<Centre>
, you could extend yourCentres
class to have an implicit conversion operator or, perhaps add a constructor to Centres that takes aList<Centre>
as a parameter.Try changing
Centres
to somthing like ...Then it will allow implicit conversion from
List<Centre>.
你正在尝试的不会起作用。
如果可能的话,您应该考虑将 Centers 重构为 has a
List
多于 is a 关系,或者至少定义一个采用IEnumerable
这样您就可以编写:
当然,这完全取决于您的具体情况,这可能不是有效的解决方案。
What you are trying wont work.
If possible you should consider refactoring Centres to a has a
List<Centre>
more than is a relationship or at least define a constructor that takes anIEnumerable<Centre>
This way you would be able to write:
Of course it all depends on your specific situation where this might not be a valid solution.
您可以做的是创建自己的包装 IList 的
IList
接口的实现。它需要更多代码,但不会像复制所有对象那么慢:
What you can do is create your own implementation of the
IList<T>
interface that wraps an IList.It takes more code, but will not be as slow as to copy all the objects: