silverlight 4.0 IEnumerable协方差的替代方案
我在我的应用程序中使用 silverlight 4.0。我的基类中有一个方法,如下所述
class BaseClass
{
protected CustomRequest GetCustomRequest(IEnumerable<IRequestType> types)
{
//Some code here...
}
}
在我的派生类中,当我像下面这样调用此方法时,我会收到错误
IEnumerable<RequestType> requestTypes = CodeToGetThis();
GetCustomRequest(requestTypes)
请注意,在调用语句中 requestTypes 的类型是 IRequestType 派生类型的可枚举类型。
由于 c#4.0 中引入了协方差,这在桌面应用程序中效果很好。但似乎对于 silverlight 4.0 来说,IEnumerable 接口并没有这样做。
那么,我应该在 silverlight 应用程序中使用什么最佳替代方法呢?
我在某处读到可以使用方法重载来完成此操作,但不知道如何执行此操作。
更新: 我在问题的第一稿中错过的一件事是,我将拥有许多 IRequestType 的派生类型,因此为每个派生类型创建重载方法对我来说将是一个困难。
I am using silverlight 4.0 in my application. I have a method in my base class as mentioned below
class BaseClass
{
protected CustomRequest GetCustomRequest(IEnumerable<IRequestType> types)
{
//Some code here...
}
}
In my derived class when I call this method like below I get error
IEnumerable<RequestType> requestTypes = CodeToGetThis();
GetCustomRequest(requestTypes)
Note here that in calling statement the type of requestTypes is a enumerable of derived type of IRequestType.
This works well in desktop applications due to introduction of covariance in c#4.0. But it seems that for silverlight 4.0 it is not done for IEnumerable interface.
So what is the best alternative approach I should use in my silverlight application for this?
I somewhere read that it can be done using method overloading but not sure how to do this.
UPDATE:
One thing I missed in the first draft of the question is, I will have many derived types of IRequestType hence craeating overloaded method for each derived type will be a difficulty for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将每个项目转换为接口即可,例如
您可以使用方法重载执行某些操作,并拥有一个采用派生/具体类型的方法,但您最终只会执行类似于上面的操作并在重载中调用原始方法。
Just cast each item to the interface e.g.
You could do something with method overloading and have a method that took your derived/concrete type but you would only end up doing something like the above and calling the original method in the overload.