GenericCollection 属性中的 C# 动态类型
我有一个控件 mycontrol.ascx
该控件有一个属性:
private GenericCollection<Item> myCollection;
public GenericCollection<Item> MyCollection
{
get { return myCollection; }
set { myCollection= value; }
}
有谁知道我如何动态地从 Item 类型更改为 Product 类型?
I have a control mycontrol.ascx
This control has a property:
private GenericCollection<Item> myCollection;
public GenericCollection<Item> MyCollection
{
get { return myCollection; }
set { myCollection= value; }
}
Does anyone know how i could dynamically change from type Item to say type Product?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。泛型的主要思想之一是它们是类型安全的。如果您希望能够更改存储
MyCollection
的类型,则需要使用Item
和Product
都来自的某种类型衍生的。You can't. One of the main ideas with generics is that they are type safe. If you want to be able to alter which type that is stored
MyCollection
, you will need to use some type from which bothItem
andProduct
are derived.由于您已指定 C# 2.0,那么我认为答案是您不能。 C# 是静态类型的,此代码将泛型集合类型化为 Item 集合。如果 Product 是 Item 的超类,那么我相信您可以将它们存储在这个集合中,但是当您从集合中检索它时,您需要查询对象类型,因为它总是作为 Item 返回。
我会向你抛出一个问题,你想在这个动态替换中实现什么目标,为什么?也许有更好的答案。
编辑
进一步考虑一下,在评论之后,您也许可以使用界面来完成此操作,即:
我还没有尝试过,远离我的开发站,但可能会引发其他人同意或纠正我:)
As you have specified C# 2.0 then I think the answer will be that you can't. C# is statically typed and this code types the generic collection to a collection of Item. If Product were a superclass of Item then I believe you could store them in this collection but you'd need to query the object type when you retrieved it from the collection as it'll always come back as an Item.
I'll throw a question back at you, what are you trying to achieve in this dynamic replacement and why? There may be a better answer.
EDIT
Thinking about it further, following the comment, you might be able to do it using an interface, i.e.:
I haven't tried it, away from my dev station but might spark some others to either agree or correct me :)