Subscribe to an event that was created in Func <>

I have a semi-general class that gets Func<>from another class to tell it how to convert data. In a somewhat truncated form, the code is as follows:

public class A
{
    public B b;

    public void init()
    {
        b = new B(ConvertRawData);
    }

    public double ConvertRawData(double rawData)
    {
        if(rawData == 1023)
            RaiseMalfunctionEvent();
        return rawData;
    }

    public void CalculateData(double rawData)
    {
        b.CalculateData(rawData);
    }
}

public class B
{
    event EventHandler Malfunction;

    Func<double, double> _converter;
    public B(Func<double, double> converter)
    {
        _converter = converter;
    }

    public void CalculateData(rawData)
    {
        var myVal = _converter(rawData);
    }
}

What I want to do is the ability to raise the event in Func<>, but be able to handle this event in class B. Currently the event is really raised in class A.

So my question is, how can I make class B without publishing a public event handler in class B? Or is it possible?

Edit , . . 1023, , , , ?

+3
3

, - : ComnversionMalfunctionException, , CalculateData(). catch .

, , converter, :

public class A
{
    public double ConvertRawData(Action raiseMalfunctionEvent, double rawData)
    {
        if(rawData == 1023)
            raiseMalfunctionEvent();
        return rawData;
    }
}

public class B
{
    event EventHandler Malfunction;

    Func<Action, double, double> _converter;
    public B(Func<Action, double, double> converter)
    {
        _converter = converter;
    }

    public void CalculateData(rawData)
    {
        var myVal = _converter(() => Malfunction(this, EventArgs.Empty), rawData);
    }
}
+1

, , , RaiseMalfunctionEvent .

+1

You can add a public method to B that raises your event and pass instance B to the converter. In the converter you can call this method.

The second way that you can change the CalculateData method to get a special exception and report it. inside the converter just drop it.

0
source

All Articles