Old FoxPro programmers love their PEMSTATUS function. For those reading this who do not know FoxPro,
let me explain what this function does. It returns a true if the existing Property, Event or Method
exists in an object and a false if it doesn't. In .NET, we can use reflection to implement this functionality.
public bool PemStatus(object o, string name, string PEM)
{
switch (PEM.ToUpper())
{
case "P" :
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(name);
if (pi == null)
return false;
else
return true;
case "E" :
System.Reflection.EventInfo ei = o.GetType().GetEvent(name);
if (ei == null)
return false;
else
return true;
case "M" :
System.Reflection.MethodInfo mi = o.GetType().GetMethod(name);
if (mi == null)
return false;
else
return true;
default :
return false;
}
}
This would then be used as follows:
if (this.PemStatus(oObject, "SetFilter", "M"))
{
// If this method call requires any parameters,
// they need to be passed in as an array of objects.
object[] parms = new object[1];
parms[0] = "MyParm";
MyFilter = (string)oObject.GetType().GetMethod("SetFilter").Invoke(oObject, parms);
}
// or
if (PemStatus(oObject, "SetFocusAtAdd") && _
(bool)oObject.GetType().GetProperty("SetFocusAtAdd").GetValue(oObject, null))
oObject.Focus();
I should also mention that this type of functionality can be handled with Interfaces as well:
if (oObject is ISetFocus && ((ISetFocus)oObject).SetFocusAtAdd == true)
oObject.Focus();
Using Interfaces is more OOP-ish, but I know that for plenty of programmers porting over old VFP code, sometimes just
finding a .NET substitute for a function that they already know how to use can be easier.
So, choose your poison. =0)
from a solution provided by Bonnie Berent in Message #1004878 and Message #1005454
|