Adding simple case where You have translation between Your enum
type and the method
itself in Dictionary
.
//Define type
public enum ReturnType {
HR,
Dev,
Finance
}
//Define methods
public void HRMethod() { Console.WriteLine("HR"); }
public void DevMethod() { Console.WriteLine("Dev"); }
public void FinanceMethod() { Console.WriteLine("Finance"); }
//Create a dictionary, where You add particular method for particular type
Dictionary<ReturnType, Action> myDict = new Dictionary<ReturnType, Action>();
myDict.Add(ReturnType.HR, HRMethod);
myDict.Add(ReturnType.Dev, DevMethod);
myDict.Add(ReturnType.Finance, FinanceMethod);
//Whenever the call occurs
myDict[ReturnType.HR].Invoke();
> HR
Edit:
With return type of IEnumerable it would look like this:
//Define methods
public IEnumerable<HR> GetHR() { return new List<HR>() {new HR() {Name="HR" } }; }
public IEnumerable<Dev> GetDev() { return new List<Dev>() {new Dev() {Name="Dev" } }; }
//Create dict + fill
Dictionary<ReturnType, Func<object>> myDict2 = new Dictionary<ReturnType, Func<object>>();
myDict2.Add(ReturnType.HR, GetHR);
myDict2.Add(ReturnType.Dev, GetDev);
//Work with it as with result type
var lRes = (myDict2[ReturnType.HR].Invoke() as IEnumerable<HR>);
Console.WriteLine(lRes.First().Name);
> HR
Solution2:
A little complicated approach is to: Create custom attribute
, over each enum value set the attribute
with value of the method to call (or name of method, see below). Once You have this, at start time with reflection You will read these attributes, create Dictionary
or a Service
, which will provide required method.
Creating own attribute with delegate isn't possible (as of: Is it possible to have a delegate as attribute parameter? ). So You have to use "hacky" solution around including type of original class and then the method name.