简体   繁体   中英

What is C# equivalent to these VB “RaiseEvent” statements?

I'm having trouble defining the event in c# that takes a byte as an arg.

Public Event LowOnFuel(ByVal FuelLevel As Byte)
...
...

public byte Drive()
{

If mFuelLevel < 30 And mFuelLevel > 0 Then _
RaiseEvent LowOnFuel(mFuelLevel)
}

Here's what I came up with:

public event LowOnFuelHandler LowOnFuel;
public delegate void LowOnFuelHandler(byte fuelLevel);
...
...
if (mFuelLevel < 30 && mFuelLevel > 0)
{
    LowOnFuel?.Invoke(mFuelLevel);
}

This must surely be a duplicate, but here's something to get you started:

For this purpose you can make events that use the built-in delegates Func or Action.

If you need a return result use Func<T> .

If you do not need to return anything use Action<T> as an event.

If you do not need to pass anything use Action (no angle brackets) as the event.

Either of them can take multiple parameters -- just declare them in the signature.

I learned from Jon Skeet the trick of attaching an empty delegate during declaration, to avoid having to test for nulls later in the code. It's completely unnecessary, especially since atomic null testing is much easier now than it used to be, but still...

You don't need to declare your delegate -- just register it with the event.

    //public event LowOnFuelHandler LowOnFuel;
    //public delegate void LowOnFuelHandler(byte fuelLevel);
    public event Action<byte> LowOnFuelEvent = delegate { };
    ...
    ...
    LowOnFuelEvent += LowOnFuelHandler;  // the actual method must match the delegate signature
    ...
    ...
    if (mFuelLevel < 30 && mFuelLevel > 0)
    {
        LowOnFuelEvent(mFuelLevel);
    }

Does that help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM