I have a semi generic class that receives a Func<> from another class to tell it how to convert data. In a somewhat stripped down fashion, the code it looks like:
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 am wanting to do is be able to raise an event in the Func<> but be able to handle that event in class B. Right now the event is actually raised in class A.
So my question is how can I make class B without exposing a public event handler in class B? Or is this even possible?
Edit As far as it being an event instead of an exception. This is external data from a sensor. The sensor sends 1023 to indicate it is in an error state, so I need to flag the data and notify the user, but would it really be an exception in my program?
I agree with others, this looks like the best approach is to use exceptions: Create a new exception class ComnversionMalfunctionException, throw it in your delegate and then catch it in CalculateData(). In the catch clause, you can then raise the event.
But if you don't want to use exceptions, you can do this by passing a delegate to the converter delegate that raises the event:
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);
}
}
If all you're trying to do is catch a possible error, you can throw an exception instead of calling RaiseMalfunctionEvent, and catch that exception when the function is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With