Convert C# statements including NSubstitute code to VB.net

人盡茶涼 提交于 2019-12-13 16:15:50

问题


While reading the NSubstitute tutorial i convert the samples written in C# to VB.net to understand the functionality, but I need your support for these (unrelated) statements, which I can't convert despite all the care taken:

1.

calculator().Received().Add(1, Arg.Is(Of Integer)(function(x) new[] {-2,-5,-10}.Contains(x)))

2.

Note: foo is a derived object from an interface with a void method called "SayHello"

foo.When(x >= x.SayHello("World")).Do(x => counter++);

3.

calculator().When(x >= x.Add(-2, -2)).Do(x => { throw new Exception(); });

Note: engine is a derived object from this interface:

public interface IEngine {
    event EventHandler Idling;
    event EventHandler<LowFuelWarningEventArgs> LowFuelWarning;
    event Action<int> RevvedAt;
}

4.

engine.Idling += (sender, args) => wasCalled = true;

5.

engine.Idling += Raise.EventWith(new object(), new EventArgs());

6.

engine.RevvedAt += rpm => revvedAt = rpm;

With your support I hope, I'm able to convert the remaining statements on my own.

Thank you in advance

Michael


回答1:


It seems you want to convert Lambda's and adding event handlers.

Lambda from c#

.Where(x => x.Foo = 1)
.Do(x => x.Bar())

translates into

.Where(function(x) x.Foo = 1)
.Do(sub(x) x.Bar())

In VB.Net you have to take into account if the Labda is actually performing a function or a sub and code it accordingly.

Adding events in c#

engine.Idling += MyEventHandler

in VB.Net

AddHandler engine.Idling, AddressOf MyEventHandler

VB.Net lets u add the event like this. Removing an event is done by the keyword RemoveHandler




回答2:


To add to Jeroen's answer, the general format for adding an event handler is:

AddHandler someObject.SomeEvent, SomeDelegate

You can use the AddressOf operator to create a delegate that refers to a named method but that is not the only way. A Lambda also creates a delegate so this:

engine.Idling += (sender, args) => wasCalled = true;

becomes this:

AddHandler engine.Idling, Sub(sender, args) wasCalled = True

Also, this line is not actually adding an event handler:

engine.RevvedAt += rpm => revvedAt = rpm;

so AddHandler won't work. I have never done it myself but I believe that you need to call Delegate.Combine for that:

engine.RevvedAt = [Delegate].Combine(engine.RevvedAt, Sub(rpm) revvedAt = rpm)


来源:https://stackoverflow.com/questions/23513811/convert-c-sharp-statements-including-nsubstitute-code-to-vb-net

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