Wrap Sub as Function for use in Lambda

帅比萌擦擦* 提交于 2019-12-10 20:51:09

问题


I have a problem with VB9 and Moq.

I need to call a verify on a Sub. Like so:

logger.Verify(Function(x) x.Log, Times.AtLeastOnce)

And my logger looks like this:

Public Interface ILogger
    Sub Log()
End Interface

But with VB this is not possible, because the Log method is a Sub, and thereby does not produce a value.

I don't want to change the method to be a function.

Whats the cleanest way of working around this limitation and is there any way to wrap the Sub as a Function like the below?

logger.Verify(Function(x) ToFunc(AddressOf x.Log), Times.AtLeastOnce)

I have tried this, but i get:

Lambda Parameter not in scope


回答1:


VB10 allows for the usage of Lambada Subs.

Have you tried a simple wrapper, such as:

Public Function Wrapper(source as Action) as Boolean  
    source.Invoke()   
    Return True 
End Function



回答2:


In 2010 if its a Sub and not a Function just replace Function with Sub.

logger.Verify(Sub(x) x.Log, Times.AtLeastOnce)



来源:https://stackoverflow.com/questions/2514196/wrap-sub-as-function-for-use-in-lambda

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