I have recently found myself in need of calling a protected method from outside of the class (short reason why: I needed to stop the object from firing OnValueChanged event when its value was changed and this was only possible via its protected Set(value, sendCallback) function).
In the end I came up with two solutions:
1.) create a derived class, and only add this function:
public void SetValue (float val, bool callback) { Set(val, callback); }
Luckily, the class was set as inheritable, so it worked.
2.) Use reflection and extension methods and do this:
public static void SetValue(this Slider slider, float val, bool callback)
{
MethodInfo sliderSetMethod = slider.GetType().GetMethod("Set", BindingFlags.NonPublic | BindingFlags.Instance);
sliderSetMethod.Invoke(slider, new object[] { val, callback });
}
This worked fine as well. Is there any reason why I should use one or another? Both of them are working fine for now, but they are obviously not really clean solutions, so I would like to know if any of them could cause problems in the future.
Aucun commentaire:
Enregistrer un commentaire