如何在.NET 2.0中为委托分配一个委托 [英] How do you do an assignment of a delegate to a delegate in .NET 2.0

查看:167
本文介绍了如何在.NET 2.0中为委托分配一个委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚回答如何传递一个通用委托作为参数。谢谢您的帮助。现在我需要知道如何将代理委托给另一个委托声明。可以这样做吗?

I just go the answer on how to pass a generic delegate as a parameter. Thanks for the help. Now I need to know how to ASSIGN the delegate to another delegate declarartion. Can this be done?

Public Class MyClass  
    Public Delegate Function Getter(Of TResult)() As TResult    

    ''#the following code works.
    Public Shared Sub MyMethod(Of TResult)(ByVal g As Getter(Of TResult))
        ''# I want to assign Getter = g  ''#how do you do it.
    End Sub
End Class

请注意,Getter现在是私有的。我如何赋值Getter = G

Notice that Getter is now private. How can I ASSIGN Getter = G

当我尝试Getter = g'时,我得到太少的类型参数编译错误。
当我尝试Getter(Of TResult)= g'我得到Getter是一个类型,不能用作表达式。

When I try Getter = g 'I get too few type arguments compile error. When I try Getter(Of TResult) = g 'I get Getter is a type and cannot be used as an expression.

你怎么做?

Seth

推荐答案

你还不能您的Getter(TResult)()委托不是一个可以分配事物的变量。它更像一个类定义。所以首先你还需要声明一个可以使用的委托变量:

You can't yet. Your Getter(Of TResult)() delegate is not a variable that you can assign things to. It's more like a class definition. So first you need to also declare a delegate variable you can use:

Public Class MyClass  
    Public Delegate Function Getter(Of TResult)() As TResult    

    Private MyGetter As Getter(Of TResult)

    Public Shared Sub MyMethod(Of TResult)(ByVal g As Getter(Of TResult))
        MyGetter = g  
    End Sub
End Class

请注意,仍然有通用类型的问题,因为您为MyMethod(Of TResult)声明的通用类型未连接到我刚刚添加的委托变量的类型。你必须使整个类通用,而不是仅仅使用它的方法。

Note that you still have an issue with the generic type, because the generic type you declared for MyMethod(Of TResult) is not connected to the type of the delegate variable I just added here. You have to make the entire class generic instead of the just the method for that to work.

我也想知道你为什么不使用现有的 Func(Of T)委托?

I'm also wondering why you don't just use the existing Func(Of T) delegate?

这篇关于如何在.NET 2.0中为委托分配一个委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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