如何定义协方差的委托函数 [英] How to define a delegate function for Contravariance

查看:95
本文介绍了如何定义协方差的委托函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在询问上一个问题时,我得到的答案是我知道的正确答案,但我仍然有(咸)不知道如何实施...

In asking this previous question, I was given an answer that I know is correct, but I still have (saldy) no clue how to implement it...

假设我有以下代码:

Public Class BaseClass
    ...
End Class

Public Class DerivedClass
    Inherits BaseClass

   ... Extra Fields, methods, etc ...
End Class

然后,在另一个过程中,我定义了以下函数:

And, then, in another procedure, I have the following function defined:

Public Function DoSomething(i as Integer, s as String, b as Boolean) As List(Of BaseClass)
  ...
End Function

并且正在使用它尝试,并在我的过程中同时返回了List(Of BaseClass)List(Of DerivedClass),但是不知道如何执行-尽管,现在我很确定(感谢

And am using it to TRY and return both List(Of BaseClass) and List(Of DerivedClass) in my procedure, but have no clue how to do it - Even though, now I'm pretty sure (thanks to the answer to my previous question) that it would involve a delegate function call.

有人可以告诉我该代码是什么样的吗?

Could someone please show me what that code would look like?

此外,尽管我对VB.Net较为满意,但我对C#的理解非常充分,能够进行转换,因此,两种解决方案都将得到极大的重视.

Also, although I'm more comfortable with VB.Net, I understand C# well enough to be able to make the conversion, so either solution would be GREATLY apprecieted.

谢谢!

基于@Servy在下面他的回答中的反馈,我了解这不是关于创建Delegate函数,而是关于从我的函数而不是List(Of BaseClass)返回IEnumerable(OF BaseClass).因此,我对其进行了更改,但仍无法正常工作... 我现在知道为什么,但是不知道该怎么办...

Based upon the feedback from @Servy in his answer below, I understand that this is not about creating a Delegate function, but rather about Returning an IEnumerable(OF BaseClass) from my function than a List(Of BaseClass). So, I changed it, but it's still not working... I now understand why, but don't know what to do about it...

当前代码:

Public Function DoSomething(i as Integer, s as String, b as Boolean) As IEnumerable(Of BaseClass)
    Dim RetVal as New List(Of BaseClass)
    Dim ToAdd as BaseClass
       ... some code ...
    ... loop 
        Retval.Add(ToAdd)
    ...
    Return RetVal
End Function

现在,我无法将代码中的RetVal更改为IEnumerable,因为这样不允许Add.

Now, I cannot change RetVal in my code to an IEnumerable since then Add is not allowed.

我该怎么做?

谢谢!

推荐答案

相对于T,类型List<T>不是协变的,因此无法实现所需的功能.要利用协方差,您需要使用支持它的类型,例如IEnumerable<T>.

The type List<T> is not covariant with respect to T, so what you want is not possible. To leverage covariance you'll need to use a type that supports it, such as IEnumerable<T>.

尽管代表自己可以利用协方差,但他们仍然需要相关类型的支持它.他们不会做任何让您将List<T>视为协变的事情.

While delegates can themselves leverage covariance, they still require the types in question to support it. They will do nothing to allow you to treat List<T> as being covariant.

这篇关于如何定义协方差的委托函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆