How do you pass a generic delegate argument to a method in .NET 2.0

随声附和 提交于 2019-12-22 10:07:15

问题


I have a class with a delegate declaration as follows...

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

    ''#the following code works.
    Public Shared Sub MyMethod(ByVal g As Getter(Of Boolean))
        ''#do stuff
    End Sub
End Class

However, I do not want to explicitly type the Getter delegate in the Method call. Why can I not declare the parameter as follows...

... (ByVal g As Getter(Of TResult))

Is there a way to do it?

My end goal was to be able to set a delegate for property setters and getters in the called class. But my reading indicates you can't do that. So I put setter and getter methods in that class and then I want the calling class to set the delegate argument and then invoke. Is there a best practice for doing this.

I realize in the above example that I can set set the delegate variable from the calling class...but I am trying to create a singleton with tight encapsulation.

For the record, I can't use any of the new delegate types declared in .net35.

Answers in C# are welcome.

Any thoughts?

Seth


回答1:


You need to add a generic type parameter to the method:

Public Shared Sub MyMethod(Of TResult) (ByVal g As Getter(Of TResult))

In C#, that would be

public static void MyMethod<TResult>(Getter<TResult> g) {



回答2:


You can make the method that accepts the generic delegate itself generic:

Public Shared Sub MyMethod(Of TResult)(ByVal g As Getter(Of TResult))
    'do stuff
End Sub


来源:https://stackoverflow.com/questions/2790978/how-do-you-pass-a-generic-delegate-argument-to-a-method-in-net-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!