silverlight 4.0 IEnumerable协方差的替代方案

发布于 2024-12-22 11:39:17 字数 713 浏览 2 评论 0原文

我在我的应用程序中使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我是男神闪亮亮 2024-12-29 11:39:17

只需将每个项目转换为接口即可,例如

IEnumerable<IRequestType> requestTypes = CodeToGetThis().Select(x => (IRequestType)x);
GetCustomRequest(requestTypes)

您可以使用方法重载执行某些操作,并拥有一个采用派生/具体类型的方法,但您最终只会执行类似于上面的操作并在重载中调用原始方法。

Just cast each item to the interface e.g.

IEnumerable<IRequestType> requestTypes = CodeToGetThis().Select(x => (IRequestType)x);
GetCustomRequest(requestTypes)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文